Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happened inside of (1).toString() and 1.toString() in Javascript [duplicate]

Tags:

javascript

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?

like image 279
soarinblue Avatar asked Aug 16 '16 07:08

soarinblue


Video Answer


3 Answers

() 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 operator
  • 1..toString() // two dots, in which the second is treated as dot operator
like image 78
Leo Avatar answered Oct 15 '22 01:10

Leo


1.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.

like image 25
Prajeet Shrestha Avatar answered Oct 15 '22 01:10

Prajeet Shrestha


Agreed with @Prajeet and @Leo

As explained in property accessor - Dot notation

1 //Next Line
.toString() //Prints "1"

From Mozilla.org: enter image description here

like image 21
NiRUS Avatar answered Oct 15 '22 01:10

NiRUS