JS Tip of the Day: Numeric Literal Formats

Numeric Literal Formats
Version: ES2015 (octal, binary), ES2020 (BigInt)
Level: Beginner

There are a number of different ways to represent numbers in JavaScript source code, whether it be integer values, decimal values, or even hexadecimal. In fact, as of ES2020, there are now also two different kinds of number types in the language. Not only do you have the classic and [questionably] dependable Number type, but now, there’s the new, massive BigInt number type. Both have their own, though very similar, literal syntax. For the Number type:

// Number literals
123 // integer
1.23 // decimal
0xDEF // hexadecimal
0o077 // octal
0b101 // binary
1.23e+5 // exponential notation

BigInt literals are similar to Number literals except they include an n suffix. BigInts also don’t support decimals or exponential syntax.

// BigInt literals
123n // integer
0xDEFn // hexadecimal
0o077n // octal
0b101n // binary

Note: You may also be familiar with an older octal style in which numbers starting with just a 0, rather than 0o, were seen as octal values. This format is considered deprecated, and in fact not allowed in strict mode, and should be avoided.

But wait! There’s more! Looking ahead to the future of JavaScript, you may see yet more ways to represent number values, both with new types and changes to the existing literal syntax.

// The future
1_000_000 // numeric separators (= 1000000)
1.23m // BigDecimal (decimal version of BigInt)
123@px // decorators (extended literals)

In fact, numeric separators are a stage 3 proposal and already available in most browsers today.

More info:

Why would I write a number 1000000 like this 1_000_000 ?
What is the meaning of separator here?

They serve no functional purpose. Instead they’re useful strictly for readability. When seeing 1000000 in code, you might not realize right away that its a million. You might have to count zeros. Its worse with a billion: 1000000000. With separators, you can more easily tell by having separators work like commas in written numbers, separating by thousand: 1_000_000_000. That’s more easily identifiable as a billion. The proposal has a few more other examples each doing something similar, separating numbers in certain ways to make them more readable.

1 Like

True. That’s a good idea. With thousands of line of code scrolling down keeping it readable is a challenge indeed.

2 Likes