For example, on reading const 1000000000, the developer might think Is this a billion? a hundred millions? Ten millions?
It becomes very difficult for the human eye to read and parse large numeric literals quickly, specifically when there are lots of repeating digits:
Now it’s relatively easier to tell that the first number is a trillion, and the second number is in the order of 9 billion.
_ as a separator appears in other programming languages also like Java, Ruby, Python, Perl, Rust, Julia, Ada, C#
An underscore character _ can be included anywhere and used between the number to improve readability. Multiple underscore characters can be used in a numeric literals.
We can use these separators at the appropriate places whenever needed, for instance, digits can be grouped per thousand.
// This is much easier to read var n = 2_565_648_775_657_678; let a = BigInt(99_999_999_999_999_999_999);
Note: Numeric separators are just for code readability, and will not change the value of the number.
Usage of numeric separators have the following limitations :
- Multiple underscores cannot be included one after the other.
//not allowed var a = 4554__88978_6;
- Underscore cannot be included at the end of the number.
// not allowed var a = 1111111111111111_;
- Underscores cannot be included after a leading 0.
// not allowed var a = 0_333333333333;
- Underscores can be included only between two digits, the following is invalid.
// A numeric separator being used in an octal integer literal: 0o123_456
- Don’t forget about exponential notation
With more number of trailing zeros, exponential notation might serve to be more convenient than grouping zeros. Compare:
const theTimeOutInMS = 10e3; /* 10 seconds */ const theTenSecondTimeOut = 10_000; /* 10 seconds */
- Numbers aren’t always the best choice to represent numeric or semi-numeric data.
Some data such as credit card numbers, phone numbers and social security numbers etc, are in some ways numbers, in other ways not: There may be non-numeric prefixes and separators and leading digits are significant. They should also not be represented in exponential notation.
// Don’t do this: const phoneNumber = 555_2368; const creditCardNumber = 378_2822_4631_0005; const socialSecurityNumber = 111_11_1111;
If used efficiently, these Separators can be helpful for the developer community in specific and might prevent numbers related issues going further.