DEV Community

Cover image for Numeric Separators in JavaScript
Suprabha
Suprabha

Posted on

Numeric Separators in JavaScript

Numeric Separators give us the ability to separate thousands with an underscore (_) in numeric literals.

How it’s useful❓

It makes our code more informative and readable.

let series = 10000;
Enter fullscreen mode Exit fullscreen mode

Numeric Separators in javascript, enables underscore as a separator in numeric literals to improve readability.

Example:

let series = 1_00_00;
Enter fullscreen mode Exit fullscreen mode

You can also use this for binary, octal, and hex numbers.

Binary Number πŸ‘»

let series1 = 0b1010_0101_1001;
console.log(series1); // 2649
Enter fullscreen mode Exit fullscreen mode

Octal Number: πŸ‘»

let series2 = 0o2_3_5_7;
console.log(series2); // 1263
Enter fullscreen mode Exit fullscreen mode

Hex Number: πŸ‘»

let series3 = 0xA_B_C_D_E;
console.log(series3); // 703710
Enter fullscreen mode Exit fullscreen mode

Few Limitation πŸ€¦β€β™€οΈ

Below limitation snippet will throw SyntaxError

  1. More than one underscore in a row is not allowed

    let series1 = 100__000;
    
  2. Can not be used after leading 0

    let series2 = 0_1;
    
  3. Not allowed at the end of numeric literals

    let series3= 100_;
    

Browser Support πŸŽ—

This feature has pretty good support in recent versions of browsers.

Check this out πŸ‘‡

browser support for numeric separators

Reference 🧐

🌟 Twitter πŸ‘©πŸ»β€πŸ’» Suprabha.me 🌟 Instagram

Top comments (2)

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Usually you'd use them where you'd use commas, dots, or spaces, depending on region, in prose. So every 3 decimal digits in the thousand/million/billion convention (10_000_000), or every 2-3 in the thousand/crore/lakh convention (1_00_00_000).

For hex, delimiting every 2 digits splits neatly into bytes (0xff_00_ff), or for binary you could split into groups of 4 to give "nibbles" - half a byte, equivalent to 1 hex digit each (0b1010_1010).

Collapse
 
nguyenit67 profile image
Nguyen

wouldn't know about this until now!