0

I'm trying to understand difference between 4 and (4).

4.toString(); // SyntaxError: Unexpected token ILLEGAL

(4).toString(); // "4"

I thought it's because toString() method is defined on Number (object) and 4 is a primitive datatype i.e.number which doesn't have toString() method.

However, how does it works for (4).toString()?

4 === (new Number(4)) // false
(4) === (new Number(4)) // false. (4) is not an instance of Number object
Rohit
  • 6,365
  • 14
  • 59
  • 90
  • Dot (`.`) doesn't only means for member access operator, it also means for decimal point in [floating-point literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Floating-point_literals). When JS interpreter meet dot after digit (`4` in your case) it expects floating-point literal, i.e. digits after dot. That's why do you need grouping operator (parens) there. – hindmost Jun 11 '15 at 18:54
  • @hindmost thank you, It makes sense now. Can you please put this comment as an answer? – Rohit Jun 11 '15 at 18:57
  • 1
    space works too: `alert( 123 .toString(36))` – dandavis Jun 11 '15 at 19:23
  • 1
    As does a second dot, e.g. `4..toString()`. (The first one is a decimal point; the second one is a member access.) –  Jun 11 '15 at 19:34

1 Answers1

3

Dot (.) doesn't only means for member access operator. It also means for decimal point in floating-point literals. When JS interpreter meets dot after digit (4 in your case) it expects floating-point literal, i.e. digits after dot. That's why do you need grouping operator (parens) there.

hindmost
  • 7,125
  • 3
  • 27
  • 39