Numeric Separators in JavaScript

Numeric separator(_) was introduced to make numbers more readable by creating a visual separation between groups of digits. The separator can be used with decimal, binary, hexadecimal or BigInt numbers. This feature was introduced in ES12.

It is difficult for humans to read large numbers quickly. What about 1000000000? Is it a billion or 10 million?. Numeric separators make developers’ life easy.

Numeric separator is purely for visual separation. It does not have any impact in the functionality. In fact, comparing a number with separator and that without it, results in true.

Position of Separator

The numeric separator can appear anywhere inside the number. Following are valid usages of numeric separators.

Numeric separator is not allowed at the end of a number. Therefore, following number is invalid.

Also, if a number starts with _, JavaScript treats it as a variable. In JavaScript, a variable can start with _.

Here _123 is considered as a variable name. Since that variable is not declared, above code will throw reference error.

Separators in Fractional Part

Numeric separators can be placed in the fractional part of a number.

Examples

Here are some examples that consider different use cases of numeric separator.

Binary Literal

A binary literal in JavaScript is denoted by prefixing a binary number by 0b. While writing a binary literal, we can place numeric separator to make it more readable.

111 is the binary equivalent of decimal number 7.

Hex Literal

A Hexadecimal literal in JavaScript is denoted by prefixing a hexadecimal number by 0x. We can include numeric separator in a hexadecimal number.

Note that the decimal equivalent of 0xFF is 255.

BigInt Literal

A BigInt literal can contain a numeric separator.

If we place an underscore _ between the number and final n, it will throw an error.

Above code results in following error:

Browser Compatibility

All the major browsers support numeric separators. We can see the precise information by visiting this CanIuse link.

This article originally published in Backbencher.dev

--

--

Learning never ends. We are exploring JavaScript, React, Deno and other crazy stuff on web right now in Backbencher.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Backbencher.dev

Learning never ends. We are exploring JavaScript, React, Deno and other crazy stuff on web right now in Backbencher.dev