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?
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?
Share Improve this question asked Mar 30, 2016 at 23:49 montrealistmontrealist 5,69312 gold badges50 silver badges72 bronze badges 3- 1 Huh, that’s strange. It’s definitely one of the strict mode restrictions according to the ES5 spec: es5.github.io/#C and es5.github.io/#x11.1.5. I’m checking to see if ES6 lifted it now (maybe for puted properties). – Ry- ♦ Commented Mar 30, 2016 at 23:53
- no error occurs means no syntax error. An object can't have multiple properties with the same name. – thangngoc89 Commented Mar 30, 2016 at 23:55
- @thangngoc89 No syntax error occurs in both modes. Any ideas why? – montrealist Commented Mar 31, 2016 at 0:03
1 Answer
Reset to default 4The 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 puted properties, so these literals would always be equivalent:
({ a: 1, ['a']: 2 })
({ a: 1, a: 2 })
But yep, everybody’s right. \o/