[go: up one dir, main page]
More Web Proxy on the site http://driver.im/

Author Information

Brian Kardell
  • Developer Advocate at Igalia
  • Original Co-author/Co-signer of The Extensible Web Manifesto
  • Co-Founder/Chair, W3C Extensible Web CG
  • Member, W3C (OpenJS Foundation)
  • Co-author of HitchJS
  • Blogger
  • Art, Science & History Lover
  • Standards Geek
Follow Me On...
Posted on 09/08/2020

Numeric Literal Separators: 2 Minute Standards

Part of #StandardsIn2Min, an effort to provide short, but useful information about standards. Follow @StandardsIn2Min for a low-stress way to keep up, 2 minutes at a time.

Imagine if we didn't have spaces...

Imagineifyouhadtoreadallofthesentencesinthispostlikethis.

What a nightmare that would be. Separators are really useful for humans. However, for most of JavaScript's history, code like this wasn't uncommon...

var x = 10000000;

This is, basically, the same problem. How many is that? It's too hard for our eyeballs to parse. If we were to display that in any form intended to be readable, we'd use some kind of separators to put these into hundred, thousands, millions, etc.. Like this... 10,000,000

Numeric separators allow us to achieve this same visual separation for readability in code, using the _ (underscore) character. The same example above could be written now as..

var x = 10_000_000;

That is, obviously, an improvement for readability.

In fact, JavaScript allows for several kinds of numeric literals beyond simple integers and these separators can be employed in all of them for visual separation. We have decimals (like 10_000.00), binary (using 'b', like 0b1101_0010), octal (using 'o' like 0o7_6_5) and hexidecimal (using '0x' like 0xA0_B2_C3), and BigInt (using 'n' like 100_000_000_000_000n).

There are just a few limitations to be aware of..

  1. You cannot use two contiguous separators
  2. You cannot end a number with a separator
  3. You cannot begin a number with a leading 0 immediately followed by a separator

That's about all there is to it. It has rich support in both modern, shipping engines and is also usable by transpilers.