Issue
Why does calling 152..toString(2)
return a binary string value of "10011000"
, when a call to 152.toString(2)
throws the following exception?
"SyntaxError: identifier starts immediately after numeric literal"
It seems to me that it's intuitive to want to use the latter call to toString()
, as it looks & feels correct. The first example just seems plain odd to me.
Does anyone know why JavaScript was designed to behave like this?
Solution
A .
after a number might seem ambiguous. Is it a decimal or an object member operator?
However, the interpreter decides that it's a decimal, so you're missing the member operator.
It sees it as this:
(10.)toString(); // invalid syntax
When you include the second .
, you have a decimal followed by the member operator.
(10.).toString();
@pedants and downvoters
The .
character presents an ambiguity. It can be understood to be the member operator, or a decimal, depending on its placement. If there was no ambiguity, there would be no question to ask.
The specification's interpretation of the .
character in that particular position is that it will be a decimal. This is defined by the numeric literal syntax of ECMAScript.
Just because the specification resolves the ambiguity for the JS interpreter, doesn't mean that the ambiguity of the .
character doesn't exist at all.
Answered By - I Hate Lazy Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.