6

See the code below:

2.toString();   // error
2..toString();  // "2"
2...toString(); // error

I want to know why 2..toString() can run without errors and what happens when it runs?

Can somebody explain it?

3
  • Curious where you came accross this example code. It's somewhat suprising that it is essentially the same as from the example link provided in @Nikolay's answer... Commented Sep 25, 2013 at 5:33
  • @Zach L I have seen it before some other place and I cannot understand it all the time.Today,I saw it again.So,I came here for the answer.It did surprise me when I opened the link provided by Nikolay,becasue I just saw another web site very similar to it.But it's another language not English. Commented Sep 25, 2013 at 6:06
  • Possible duplicate of Calling member function of number literal Commented Oct 14, 2016 at 18:58

1 Answer 1

8

http://shamansir.github.io/JavaScript-Garden/en/#object

A common misconception is that number literals cannot be used as objects. That is because a flaw in JavaScript's parser tries to parse the dot notation on a number as a floating point literal.

2.toString(); // raises SyntaxError

There are a couple of workarounds that can be used to make number literals act as objects too.

2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first
Sign up to request clarification or add additional context in comments.

1 Comment

@Nikolay Tlnv: Thanks.When the JavaScript's parser meets 2.toString(),it doesn't know how parse the dot as 2.|toString() or 2|.toString().If there is another dot or space left to the dot the parser can treat it as a certain way.Is it right?

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.