Underscores in numbers

By

Learn how JavaScript numeric separators let you add underscores inside numbers like 1_000 for readability, a feature available since ECMAScript 2021.

~~~

TIL you can add underscores in the middle of any number in JavaScript, to improve its readability according to what the number means to you:

1_000 //1000
2_3_4 //234

It’s a relatively new feature (since ECMAScript 2021), but supported by all major browsers since years.

The underscore is called a numeric separator. It’s purely visual. The engine strips it, so 1_000 and 1000 are the exact same number.

Where you can use it

It works with decimals, with binary and hex literals, and with BigInt:

const price = 1_299.99
const budget = 1_000_000
const mask = 0b1010_0001 //161
const big = 123_456n

I find it most useful for large amounts. Reading 1000000000 means counting zeros with your finger. Reading 1_000_000_000 is instant, like the commas you’d write on paper.

The rules

There are a few spots where the underscore is not allowed. You can’t put it at the start or end of the digits, you can’t have two in a row, and you can’t place it next to the decimal point. All of these are syntax errors:

1000_ //SyntaxError
1__000 //SyntaxError
1_.5 //SyntaxError

The nice thing about these being syntax errors is that you find out immediately, not at runtime.

Watch out when parsing strings

Numeric separators only work in number literals, in your source code. They do not work when you convert strings to numbers:

Number('1_000') //NaN
parseInt('1_000') //1

Number() rejects the whole thing and gives you NaN. parseInt() is sneakier: it parses up to the first character it doesn’t understand, so it stops at the underscore and quietly returns 1.

That second one is the dangerous case, because nothing fails loudly. So if you store numbers as strings, in a database or in a config file, leave the underscores out. They belong in code, for humans.

See https://v8.dev/features/numeric-separators

~~~

Related posts about js: