Skip to content Skip to sidebar Skip to footer

1.toString() SyntaxError In Javascript

Why the first line below gives error although the second and third lines work fine? 1.toString(); // SyntaxError (1).toString(); // OK 1['toString'](); // OK

Solution 1:

The . 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.


Solution 2:

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.


Solution 3:

In Javascript, using the dot (.) can be interpreted in one of two ways:

  1. As a Property Accessor (e.g., var prop = myObject.prop;).
  2. 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 accomplish this:

// Via white-space after the numeric literal
1 .toString();

1
.toString();

// Via a grouping-operator, aka, parentheses
// @see https://developer.mozilla.org/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']();

Post a Comment for "1.toString() SyntaxError In Javascript"