Why the first line below gives error although the second and third lines work fine?
1.toString(); // SyntaxError
(1).toString(); // OK
1['toString'](); // OK
Why the first line below gives error although the second and third lines work fine?
1.toString(); // SyntaxError
(1).toString(); // OK
1['toString'](); // OK
Share
Improve this question
asked Oct 3, 2012 at 3:45
scusyxxscusyxx
1,2441 gold badge8 silver badges9 bronze badges
2
- 1 And "they" want to make javascript strictly typed! – RobG Commented Oct 3, 2012 at 3:57
- Don't worry about him. The specification authors are making it strictly typed. – Amir Rahnama Commented Nov 12, 2015 at 8:56
4 Answers
Reset to default 12The .
presents ambiguity. Is it a decimal, or a property accessor?
The interpreter sees it as a decimal, so you can use ..
to allow both the decimal, then the property syntax.
1..toString();
Or use one of the other ways you show to resolve the ambiguity.
The parser is trying to treat 1.
as the start of a floating-point literal -- only toString
turns it into an invalid number.
Compare with:
1.0.toString()
In (1).toString()
, (1) forces it to evaluate before .toString() so it works.
In 1.toString()
, 1 is not a valid identifier so it does not work.
In Javascript, using the dot (.
) can be interpreted in one of two ways:
- As a Property Accessor (e.g.,
var prop = myObject.prop;
). - As part of a Floating-point Literal (e.g.
var num = 1.5;
).
In the above case, the leading 1.
in 1.toString()
is interpreted as a floating point number, hence the error:
SyntaxError: identifier starts immediately after numeric literal (learn more)
This is the same error you get if you try and declare a variable that starts with a number: var 1person = 'john';
To prevent the interpreter from seeing the 1.
as a decimal and instead see it as accessing a property on our literal 1
, there are several ways to acplish this:
// Via white-space after the numeric literal
1 .toString();
1
.toString();
// Via a grouping-operator, aka, parentheses
// @see https://developer.mozilla/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Grouping_operator
(1).toString();
// Via an additional dot. Made clearer with parentheses as `(1.).toString()`
1..toString();
// Via an explicit fractional part (because `1. === 1.0`)
1.0.toString();
// Via bracket notation
1['toString']();
1.['toString']();
1.0['toString']();