DEV Community

Samuel Rouse
Samuel Rouse

Posted on • Edited on

1

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!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more