This content originally appeared on DEV Community and was authored by Samuel Rouse
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.
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
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.
So how do we access prototype methods? With a second period.
200..toString(); // '200'
200..toFixed(2); // '200.00'
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'
But you'll miss out on silly code like this:
[...3..toFixed(2)][1]; // '.'
Hope you enjoyed!
This content originally appeared on DEV Community and was authored by Samuel Rouse
Samuel Rouse | Sciencx (2025-02-28T23:35:53+00:00) Number Methods: JavaScript Quick Bits. Retrieved from https://www.scien.cx/2025/02/28/number-methods-javascript-quick-bits/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.