Why does “new Date().toString()” work given Javascript operator precedence?

The syntax is

MemberExpression :
    PrimaryExpression
    FunctionExpression
    MemberExpression [ Expression ]
    MemberExpression . IdentifierName
    new MemberExpression Arguments

new foo().bar cannot be parsed as new (foo().bar) because foo().bar is not a MemberExpression. Moreover, new foo() cannot be parsed as new (foo()), for the same reason. Conversely, new foo.bar is parsed as new (foo.bar) because foo.bar is a valid MemberExpression (an interpretation (new foo).bar is impossible because the grammar is greedy).

That is, the precedence rule is: dot beats new, new beats call (parens).

.  -> new -> ()

Furthermore, looking directly at the grammar demystifies the syntactic sugar that turns new Foo into new Foo(). It’s simply NewExpression ← new NewExpression ← new PrimaryExpression:

NewExpression :
    MemberExpression
    new NewExpression

Leave a Comment

File not found.