Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 2..toString() work? [duplicate]

Tags:

javascript

Why does 2..toString() return 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());
like image 779
Larry Battle Avatar asked Mar 17 '13 08:03

Larry Battle


2 Answers

That's because 2. is parsed as 2.0, so 2..toString() is equivalent to 2.0.toString(), which is a valid expression.

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

like image 84
Frédéric Hamidi Avatar answered Oct 17 '22 00:10

Frédéric Hamidi


2 is just a number, it doesn't have any methods to call.

2. can be coerced into a string, which is an object (i.e. '2.0'), hence can have the method.

Just 2.toString() will be parsed as 2.0tostring(), which of course doesn't make sense.

Looking at how the two are parsed:

enter image description here

vs

enter image description here

The tool to generate these is here by the way: http://jsparse.meteor.com/

like image 6
2 revs Avatar answered Oct 17 '22 02:10

2 revs