3

Why does (1).constructor return ƒ Number() { [native code] }, whereas 1.constructor returns Uncaught SyntaxError: Invalid or unexpected token?

What is the difference between the two and what exactly happens under the hood?

Andrei Rosu
  • 1,169
  • 2
  • 10
  • 26
  • (1) creates an expression that evaluates to a Number. Hope I got it right this time. – connexo Feb 26 '18 at 12:13
  • 1
    The parser is greedy and gets as much from the input as it can while the expression it parses is still correct. When it parses `1.constructor`, `1.` is a valid floating point number followed by `constructor` and this breaks the syntax rules. On the other hand, `(1)` is an expression that contains the number `1` between parentheses and `.` is not interpreted as a decimal dot any more. – axiac Feb 26 '18 at 12:17

1 Answers1

2

Your digit is part of a number literal. The first . in a numeric literal is the floating point and not the start of a property reference.

You can see this in the spec:

DecimalIntegerLiteral . DecimalDigits opt ExponentPart opt

By wrapping the numeric literal in parentheses, you separate it from the . so the . is not treated as part of the numeric literal (and so can be used to read a property of the resulting object).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    We got a [boatload of duplicates](https://stackoverflow.com/questions/linked/9380077?lq=1) for this already… – Bergi Feb 26 '18 at 12:15