JavaScript Quick Bits: Number Methods
Samuel Rouse

Samuel Rouse @oculus42

About: Tech generalist specializing in UI development. UI Architect by day. Playing with JavaScript for over 25 years.

Location:
Maine
Joined:
May 10, 2022

JavaScript Quick Bits: Number Methods

Publish Date: Feb 28
1 0

We rarely need to access prototype methods on primitive types like plain numbers and strings, but we can...even when it seems like we can't.

// Primitive access
'word'.split(''); // [ 'w', 'o', 'r', 'd' ]

// What about numbers?
200.toString(); // SyntaxError: Identifier directly after number.
Enter fullscreen mode Exit fullscreen mode

That doesn't seem to work. This is because all regular numbers are decimals in JavaScript (double-precision floats, to be specific), so the period as part of the number has priority over the dot period as dot notation.

1;   // 1
1.;  // 1
1.0; // 1

[ 1, 1., 1.0 ].every(value => value === 1); // true
Enter fullscreen mode Exit fullscreen mode

As far as the JavaScript engine is concerned, these are the same code:

200.toString(); // SyntaxError: Identifier directly after number.
200toString();  // SyntaxError: Identifier directly after number.
Enter fullscreen mode Exit fullscreen mode

So how do we access prototype methods? With a second period.

200..toString(); // '200'
200..toFixed(2); // '200.00'
Enter fullscreen mode Exit fullscreen mode

The first period is part of the number; the second period is for dot notation property access.

If two periods seems wrong, you can use bracket notation instead.

200['toFixed'](2); // '200.00'
Enter fullscreen mode Exit fullscreen mode

But you'll miss out on silly code like this:

[...3..toFixed(2)][1]; // '.'
Enter fullscreen mode Exit fullscreen mode

Hope you enjoyed!

Comments 0 total

    Add comment