Search code examples
javascripttheory

JS: two or more object properties with the same name in non-strict mode?


Reading David Flanagan's Definitive Guide (6th edition), stumbled on this:

In strict mode, it is a syntax error for an object literal to define two or more properties by the same name. (In non-strict mode, no error occurs.)

I can't find any examples - is it even possible? I tried

var obj = {prop: 'foo', prop: 'bar'};

...but of course I end up with only one property (Object {prop: "bar"}), in both strict and non-strict modes.

Is this implementation-dependent? The book is a 2011 edition, ECMAScript 5 is in there.

Should I be reading a newer book?


Solution

  • The book is right; the ES5 specification states that defining multiple properties with the same name in an object literal is a syntax error.

    See section 11.1.5 around here:

    If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true

    and the informative Annex C:

    It is a SyntaxError if strict mode code contains an ObjectLiteral with more than one definition of any data property (11.1.5).

    The implementations you’re testing are also right, however, as the current ECMAScript specification is ES2015, which drops this restriction! It’s not listed in its Annex C or anywhere else.

    If I had to guess, it would be that the reason for this removal was consistency with computed properties, so these literals would always be equivalent:

    ({ a: 1, ['a']: 2 })
    ({ a: 1, a: 2 })
    

    But yep, everybody’s right. \o/