What Are Numeric Separators in JavaScript?

Introduced in ES12, an underscore (_) can be used as a numeric separator to act as a visual separation between groups of digits. The purpose of having numeric separators is to improve readability of numeric literals. For example:

// ES12+
const million = 1_000_000;

console.log(million); // 1000000
console.log(million === 1000000); // true

You can actually use numeric separators with all kinds of numeric literals to improve readability:

// ES12+
const decimal = 1_000.123_456;

console.log(decimal); // 1000.123456
console.log(decimal === 1000.123456); // true
// ES12+
const bigint = 1_234_567n;

console.log(bigint); // 1234567n
console.log(bigint === 1234567n); // true
// ES12+
const hex = 0x6F_3A_45;

console.log(hex); // 7289413
console.log(hex === 0x6F3A45); // true
// ES12+
const oct = 0o123_456;

console.log(oct); // 42798
console.log(oct === 0o123456); // true
// ES12+
const binary = 0b0101_0110;

console.log(binary); // 86
console.log(binary === 0b01010110); // true

The order of the underscores can be whatever you want it to be; it does not need to be in a set sequence or pattern:

const phoneNumber = 1_123_4567;

Do not use number separators directly with parsing functions (such as Number(), parseInt(), parseFloat(), etc.) as they would yield unexpected results.

The following are not allowed and would raise an error:

// SyntaxError: Only one underscore is allowed as numeric separator
// SyntaxError: Numeric separators are not allowed at the end of numeric literals
// SyntaxError: Numeric separator can not be used after leading 0
// SyntaxError: Invalid or unexpected token
// SyntaxError: Invalid or unexpected token
// SyntaxError: Invalid or unexpected token

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.