Reputation: 6701
Can someone explain the behaviour below, it is about the temporary wrapper objects in JS, but when I try to use them on number literal they fail. Am I mistaken or this changed recently, I tried on V8 and Gecko, same story.
'stringWrapper'.charAt(0);
"s"
1.toString();
VM8363:2 Uncaught SyntaxError: Unexpected token ILLEGAL(…)InjectedScript._evaluateOn @ VM8253:875InjectedScript._evaluateAndWrap @ VM8253:808InjectedScript.evaluate @ VM8253:664
typeof 1
"number"
(1+0).toString();
"1"
typeof (1+0)
"number"
Upvotes: 1
Views: 92
Reputation: 1056
More interesting JavaScript things: 1 .toString()
is valid! 1. toString()
is not.
You may enjoy Kyle Simpson's video on weird JavaScript quirks
Upvotes: 0
Reputation: 47222
This is an interesting "feature" in JavaScript and other dynamically typed languages, like Python, where you can call methods or access properties on an integer.
What's actually happening is that the engine sees, or lexes, the 1.toString()
as a floating point number where the toString()
part is where the first decimal should be.
The solution is either to double-dot it, 1..toString()
and omit the trailing decimal or wrap the number within parenthesis (1).toString()
to evaluate the number and then call toString
on the result.
Upvotes: 3