javascriptidentifierecma262

In what places in the grammar is it permitted to use any identifier token, including a reserved word?


In Javascript there are various reserved words that cannot be used inside Identifiers; some of those are actually reserved for future use. To clarify a bit, an Identifier is an IdentifierName but not a reserved word. The exact grammar of IdentifierNames is not relevant here.

According to the last paragraph here, though, it seems that there are some place where it is valid to use any IdentifierName, even if it is a reserved word. The article mentions as valid

a.import
a["import"]
a = { import: "test" }

While it is clear to me that the second form is legal, I always thought that the first and the third were not.

In fact, this resource denotes

foo.if

as invalid code.

Are there some places were reserved words are actually valid?

As a motivation, I am writing an API where it would make sense to pass objects of the form

{
    in: foo,
    out: bar
}

but I don't want to force users to put brackets around in.


Solution

  • This is a change in ECMA-262 between editions 3 and 5 (which you can get here).

    In both editions, section 7.6 defines an Identifier as

    Identifier ::
        IdentifierName but not ReservedWord
    

    However, in section 11.2.1, property accessors using dot notation were changed from

    MemberExpression . Identifier
    CallExpression . Identifier
    

    in edition 3 to

    MemberExpression . IdentifierName
    CallExpression . IdentifierName
    

    in edition 5, ie using reserved names as dot accessors is indeed legal now.

    I don't know if this change was made just because the restriction to Identifier is syntactically unnecessary because none of the reserved words could ever legally follow a ., or if it also codified existing practice of various implementations.

    PS: After some digging, I found the following in a mail from Allen Wirfs-Brock, project editor for edition 5:

    The ES3 grammar does not allow reserved words (such as true and false) to be used as a PropertyName or to the right of the period in a MemberExpression. Your tests verify that most implementations conform to that restriction while FF has a "non-standard" extension that allows reserved words (or at least the ones you tested) to be used in those contexts.

    ES3.1 intentionally adopted the FF extension as a standard part of the language, so when the other implementation are eventually updated to support ES3.1 they should no long report errors for your test cases.

    Note that ECMAScript 3.1 was the original name for what is now known as ECMAScript 5.