DEV Community

Samuel Rouse
Samuel Rouse

Posted on • Edited on

JavaScript Quick Bits: Number Methods

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!

Top comments (0)