Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Function toString

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?

like image 253
Joyce Lee Avatar asked Sep 25 '13 05:09

Joyce Lee


People also ask

What is toString function in JavaScript?

The toString() method returns a string as a string. The toString() method does not change the original string. The toString() method can be used to convert a string object into a string.

Is there a toString method in JavaScript?

toString . For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.

What is the difference between toString () and valueOf () in JavaScript?

If the hint is String , then toString is used before valueOf . But, if the hint is Number , then valueOf will be used first. Note that if only one is present, or it returns a non-primitive, it will usually call the other as the second choice.

What is toString 2 JavaScript?

toString(2) converts to binary, the tilde ( ~ ) is a bitwise unary operator stackoverflow.com/questions/791328/…


1 Answers

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
like image 178
Nikolay Talanov Avatar answered Sep 30 '22 21:09

Nikolay Talanov