Reputation: 5600
For example,
1.toFixed(2) // Uncaught SyntaxError: Invalid or unexpected token
(1).toFixed(2) // "1.00"
let num = 1
num.toFixed(2) // "1.00"
At the same time, you don't have to wrap parenthesis around strings to call methods on them
'yo'.repeat(3) // "yoyoyo"
What is the rule at play here and where else does it apply? Guessing it has something to do with the dot being misinterpreted as a decimal for numbers?
Upvotes: 3
Views: 204
Reputation: 10081
..
if you don't like parenthesis. The first one for decimals, the second one to call the method.let num = 1;
console.log(num.toFixed(2));
// console.log(1.toFixed(2)); // ERROR
console.log((1).toFixed(2));
console.log(1..toFixed(2));
Upvotes: 1
Reputation: 227280
As others have stated, JavaScript is looking for more numbers after the decimal point. It thinks you are trying to type a float like 1.2
and it doesn't like that t
there, it's not a number.
Interestingly, you can do this without parenthesis or making variable by using 2 decimal points. Like this: 1..toFixed(2)
. I guess you can also do 1.0.toFixed(2)
if you want.
Upvotes: 1
Reputation: 2407
Because the interpreter is looking for more digits (decimal values), not keywords or methods.
Upvotes: 3