Why does 2..toString () work?

Why 2..toString() returns 2 , but 2.toString() throws this error?

Example:

 console.log(2..toString()); // prints 2 // Firefox throws the error // `SyntaxError: identifier starts immediately after numeric literal` console.log(2.toString()); var x = 2; console.log(x.toString()); // prints 2 // Firefox throws the error //`TypeError: XML descendants internal method called on incompatible Number` console.log(x..toString()); 
+7
source share
5 answers

2 is just a number, it has no methods to call.

2. can be forced into a string that is an object (i.e. '2.0' ), therefore it can have this method.

Just 2.toString() will be parsed as 2.0tostring() , which of course makes no sense.

A look at how they are analyzed:

enter image description here

against

enter image description here

A tool to create them here, by the way: http://jsparse.meteor.com/

+4
source

This is because 2. parsed as 2.0 , therefore 2..toString() equivalent to 2.0.toString() , which is a valid expression.

2.toString() , 2.toString() other hand, is parsed as 2.0toString() , which is a syntax error.

+8
source
 2.toString() 

The interpreter sees 2 and thinks "oh, number!". Then he sees the dot and thinks β€œoh, decimal number!”. And then he goes to the next character and sees t , and he gets confused. " 2.t not a valid decimal number," the message says, because it generates a syntax error.


 2..toString() 

The interpreter sees 2 and thinks "oh, number!". Then he sees the dot and thinks β€œoh, decimal number!”. Then he sees another point and thinks: β€œOh, I think this is the end of our number. Now we look at the properties of this object (number 2.0).” Then it calls the toString method of object 2.0 .

+4
source

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString

As the Number object overrides the toString method of the Object, you must first use the paranthesis explication to indicate that it is a number, not an object.

I assume that 2. implicitly defines it as a float, which can then use the .toString() method of the Number object, rather than the method of the Object object.

+2
source

2..toString() will be interpreted as 2.0.toString() .

Actually, 2. is a number: console.log(typeof 2.); will indicate: number

+1
source

All Articles