Use-Cases of this tutorial
- Know how to improve readability of large numbers in Javascript (for example the number 111111111111111111111111)
- Know about numeric separators recently added in Javascript.
Numeric separators can be used to improve readability of large numbers in Javascript. For example the number 111111111111111111111111, which is difficult to read, can be alternately written as 111_111_111_111_111_111_111_111
Including a large number in Javascript code can hamper readability, and this may lead to possible bugs. Situation is even worse when there are repeating digits in the number.
// Developer can read this number incorrectly and this may lead to bugs
var n = 2565648775657678;
// difficult to read
let a = BigInt(99999999999999999999);
As a solution to this, numeric separators have been introduced in Javascript. An underscore character _ can be included anywhere between the number to improve readability. Multiple underscore characters can be used.
These separators can be used in appropriate places, for example, 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);
Obviously numeric separators are just for code readability, and will not change the value of the number.
Notes
Usage of numeric separators are bound to some 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;