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());
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.
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:
vs
The tool to generate these is here by the way: http://jsparse.meteor.com/
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