Why 1..toString() return "1" in JavaScript?

Why 1..toString() return "1" in JavaScript?
Photo by Minh Trí / Unsplash

The expression 1..toString() returns the string "1". Here's how it works:

  1. 1. (the first . after 1): 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 wrote 1.toString(), JavaScript would think you're trying to access a property on 1 (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.
  2. toString(): This is a method of the Number object in JavaScript. It converts the number 1 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 the 1 as part of a decimal number, expecting something like 1.0. It doesn’t know that you intend to call the toString() method.
  • 1..toString() works because the first . after 1 is interpreted as the decimal point (so it's treated as 1.0), and the second . is used to access the method toString().

Key difference:

  • 1.toString(): This fails because JavaScript expects the dot to be part of the number literal, so it doesn't recognize toString() as a method call.
  • 1..toString(): The first dot forms the complete numeric literal (1. or 1.0), and the second dot accesses the method toString().

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. 1..toString()
  2. (1).toString() — parentheses help clarify the numeric literal.
  3. 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.

Support Us

Subscribe to Buka Corner

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe