4

The following JavaScript code:

console.log(2 .toString());

Outputs “2”.

(Note: The space between the '2' and '.x' is intended)

Simple question: Why? Especially when the following yield syntax errors:

console.log(2.toString());
console.log(2. toString());

1 Answer 1

8

The . is an operator. The 2 is a number. The x is (treated as) a property name.

A floating-point numeric constant must not have embedded spaces. Thus, 2 .x is an expression calling for the constant 2 to be promoted to a Number object, and then the property called "x" is examined. There isn't one, of course, so the value is undefined.

You can get the same effect a little more explicitly with

alert((2).x);

Note that

alert("Hello".x);

is somewhat similar: in that case, it's not a numeric constant, it's a string constant. It's less peculiar because there's no syntactic funny business involved, but otherwise the interpreter does similar things when evaluating. The string constant is first converted to a String object, and then the "x" property is fetched.

edit — to clarify a little, 2.x is an error because it's parsed as a numeric constant ("2.") followed by the identifier "x", and that's a syntax error; two values placed next to each other like that with no intervening operator do not form any sort of construct in the language.

Sign up to request clarification or add additional context in comments.

6 Comments

Holy assignment Batman. Well spotted. This proves it: Number.prototype.x="Hello there"; alert(2 .x);
So, by logical extension alert(2 .valueOf()); will alert "2"! Hehe!
But this does not: Number.prototype.x='bla'; alert(2[x]);
alert(2..valueOf()); or alert(2..toString()); would also work. @Pointy: nice answer.
But @mplungjan you forgot the quotes around "x" in that - or try just like the example in the OP, "2 .x" or "(2).x".
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.