sdfsdf
sdfsdf

Reputation: 5600

Why do you have to wrap parenthesis around a number to called toFixed on it?

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

Answers (3)

Takit Isy
Takit Isy

Reputation: 10081

  • When using a variable, Javascript is confident that you're not going to add decimals after the point.
  • When not using a variable, Javascript thinks that you are going to add decimals after the point.
  • When you wrap your number with parenthesis, you say that the number is finished, and everything is fine again.
  • You can also use .. 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

gen_Eric
gen_Eric

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

Ben Steward
Ben Steward

Reputation: 2407

Because the interpreter is looking for more digits (decimal values), not keywords or methods.

Upvotes: 3

Related Questions