10

Some languages, like Java and C++, allow you to use numeric separators. To improve readability, you can group digits per thousand:

1_000_000_000

But not only per thousand; you can use it anywhere really. Say you have some value in centimeters. Separating it like this makes it easier for humans to read it as meters:

10_00  // 10 meters

Wouldn't it be great if we could have this in JavaScript as well?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lucio Paiva
  • 19,015
  • 11
  • 82
  • 104

3 Answers3

17

Guess what? It is becoming a thing now :-)

And it works for any numeric base:

const decimal = 1_234;
const binary = 0b1000_0101;
const hex = 0x12_34_56_78;

As of May 2020, it is supported by all major browsers (Chrome, Firefox, Edge, Safari, Opera) (source 1, source 2). And if you're working on the server side, Node.js v12.5.0 is already supporting it as well. Oh, and Electron too.

Interesting note: although supported by all browsers, this is not part of any ECMAScript version yet. It is still a stage 3 proposal (though when it gets to 4 it's basically ready to be released). Good to see that browsers are quickly catching up with new proposals.

Lucio Paiva
  • 19,015
  • 11
  • 82
  • 104
  • I'm trying to make this work with my app but I'm getting a `Failed to compile` error. I'm using ecma version 2018. What am I missing? – Mix Master Mike Jan 24 '20 at 02:49
  • 2
    @MixMasterMike this is not part of ECMAScript 2018 (not even 2019). It is a stage 3 proposal, not yet ready for release. I edited my answer to add that info. You will only be able to get this feature via v8 and projects that use it (Chrome, Nodejs, Electron, etc). Whatever the platform you're using, be sure to check if it uses at least v8 7.5. Well, it looks like Babel also supports it (see other answer). – Lucio Paiva Jan 24 '20 at 13:02
  • Ah, makes sense. Thanks for clarifying! – Mix Master Mike Jan 24 '20 at 17:31
1

It sounds interesting. I found this worked on the latest version of Chrome.

Babel also supports it in stage-0. Then you can use Babel to transpile to ECMAScript 2015 (ES6).

Try it on Babel.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Long Nguyen Duc
  • 1,317
  • 1
  • 8
  • 13
0

Constants are better for reading in some cases:

const G = 1**9;
const M = 1**6;
const k = 1**3;
const cm = 0.01;

var size = 5 * G;
var count = 10 * k;
var length = 100 * cm;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131