56.toString
not works throws exception . 56..toString
works fine .
Can anyone explain what is the difference between these two statements ?
56.toString(); //throws exception
56..toString(); //Works Fine.
How it works?
56.toString
not works throws exception . 56..toString
works fine .
Can anyone explain what is the difference between these two statements ?
56.toString(); //throws exception
56..toString(); //Works Fine.
How it works?
Numeric literals are somewhat special, because the property access .
can be conflated with a decimal point .
When the parser encounters 56.
it expects a digit (or nothing) to follow this. When you write 56..toString()
you are getting the toString()
of 56.0
that's not problem for toString() method, just the 56. the toString will think it's 56.0, but it have not the '0', so it will fail.
work fine or like this:
(56.).toString()
or
56..toString()
The problem here is when you type
56.toString()
JavaScript thinks 56 is a variable name, and you are trying to access it's toString() method. But this doesn't work because 56 is not a variable, and it's not even a valid variable name, therefore results in a compile error. (Variable name must start with a letter)
Check here for JS variable naming rules
But when you add a dot behind the 56 (56.) it becomes a number literal, and language creates an instance of Number class for that, then tries to resolve toString() method on the Number instance. Since the Number class defines a method called toString() and then it works.
56..toString();
Is equivalent to
(new Number(56.)).toString();
Key to understand here is difference between Number literal (56.) and method access operator (variable.methodName() )