In JavaScript console, if typing below:
1.toString(); // Uncaught SyntaxError: Invalid or unexpected token
(1).toString(); // "1"
What is going on inside JS compiler with the two statements?
()
is grouping operator, which returns the value of the expression inside it. Here in your case, it's 1
, a primitive number. So it can be boxed to a Number
object and call its method toString
.
However for 1.toString()
, the JS engine cannot determine what does .
mean - a dot operator (for object methods), or a float number point?
To solve this confusion, without the grouping operator, you have two approaches:
1 .toString()
// a whitespace, works similar as grouping operator1..toString()
// two dots, in which the second is treated as dot operator1.toString()
is treating 1 as an integer and expecting number after the .
In (1).toString()
, (1) is an expression in which a .
is used to call a method.
Agreed with @Prajeet and @Leo
As explained in property accessor - Dot notation
1 //Next Line
.toString() //Prints "1"
From Mozilla.org:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With