Why 1..toString() return "1" in JavaScript?
The expression 1..toString()
returns the string "1"
. Here's how it works:
1.
(the first.
after1
): This is treated as part of the numeric literal. JavaScript requires the second.
to distinguish between a floating-point number and a method call. If you just wrote1.toString()
, JavaScript would think you're trying to access a property on1
(a number) but wouldn't know where the number ends and where the property access begins. So, you add an extra.
to make it clear.toString()
: This is a method of theNumber
object in JavaScript. It converts the number1
to its string representation.
Thus, the code 1..toString()
calls the toString()
method on the number 1
and returns the string "1"
.
Based on that information, we can say 1.toString()
will not the same like 1..toString()
.
Why?
1.toString()
will result in a syntax error because JavaScript interprets the first dot after the1
as part of a decimal number, expecting something like1.0
. It doesn’t know that you intend to call thetoString()
method.1..toString()
works because the first.
after1
is interpreted as the decimal point (so it's treated as1.0
), and the second.
is used to access the methodtoString()
.
Key difference:
1.toString()
: This fails because JavaScript expects the dot to be part of the number literal, so it doesn't recognizetoString()
as a method call.1..toString()
: The first dot forms the complete numeric literal (1.
or1.0
), and the second dot accesses the methodtoString()
.
Example:
1.toString()
→ Syntax Error: The parser doesn’t know where the number ends and the method call starts.1..toString()
→"1"
: The first dot finalizes the numeric literal, and the second dot allows the method call.
Alternative ways to call toString()
on a number:
1..toString()
(1).toString()
— parentheses help clarify the numeric literal.1.0.toString()
So while both aim to call toString()
on the number 1
, only 1..toString()
or (1).toString()
works in this case.
Hope it helps.