What\'s the difference between the following code?
var a = 1;
a.toString(); // outputs: \"1\"
But this throws an error:
1.t
The toString() method returns a string representing object.
So when you call:
a.toString();
You are actually operating on an object. You are actually creating a built-in object when you define a variable(in this case it is a number).
When you do this:
1.toString();
toString() doesn't see 1
as an object or a variable(both are the same in this scenario) because it fails the rule:
Variable must begin with a letter
Here 1
doesn't begin with a letter. So toString()
knows it is not operating on an object and throws an error.
With method invocations, it is important to distinguish between the floating-point dot and the method invocation dot.
Thus, you cannot write 1.toString();
you must use one of the following alternatives:
1..toString()
1 .toString() //space before dot
(1).toString()
1.0.toString()
Try to Change the Syntax,
(1).toString()
Numbers can have decimals, so the syntax for ending in a decimal is a bit ambiguous when you go to parse the code, use parenthesis to be valid. It's a bit clearer when you see that this is also valid:
(1.).toString()
However with just
1.toString() it's trying to parse as a number with a decimal, and it fails.