Why is object with duplicated property accepted in JavaScript?

javascript

Solution

What you state has no problem if you assign it to a variable, if you don't however, you get the error you mention. Which makes all the difference from a syntax point of view.

When you wrap any structure in parens you are causing that syntax to be evaluated as an expression, the result of which is stored as a temporary variable. The error I get when not doing so in Firefox is unexpected label or invalid label, so it seems without assignment, or parens, this object construction is not treated as an object construction - instead it is treated as a block with multiple label statements that are defined illegally:

{
  a: function(){
    alert('a');
  },
  b: function(){
    alert('b');
  }
}

The above should be totally acceptable as an object, however you get a similar error if you evaluate it without assinging it to some form of variable, or evaluating it with parens. Put simply the duplication of the attribute name is not causing the error :)

Basically imagine your first example, but like this:

function (){
  "a": 4,
  "b": 5
}

That is roughly how these browsers are treating it, which is now obviously illegal javascript syntax... whereas it wasn't so obvious before.

Problem

I was expecting JavaScript to reject objects with duplicated properties as invalid but it accepts them in some cases. `{"a":4,"a":5}` results in an `SyntaxError` at least in Firefox and Chrome which seems obvious due to the property `a` being defined twice. However `({"a":4,"a":5})` evaluates just fine and results in an object `{"a":5}` in both Firefox and Chrome. Why is the expression with the parenthesis accepted? Summing up the responses: The first example is simply not the construction of an object but a block of labeled statements. Duplicated properities in objects are perfectly valid in which case the last definition wins. Thanks a lot for your answers!

Original source