What is JavaScript shorthand property? [duplicate]

var obj = { prop = [1,2,3] };

The code above contains a typo, there should be a colon instead of =. But what surprised me was the VM error message:

var obj = { prop = [1,2,3] };
            ^^^^^^^^^^^^^^
SyntaxError: Invalid shorthand property initializer

I searched for "JavaScript shorthand properties" but this term is still not clear to me. What does "Shorthand property" means in context of this error message?


Solution 1:

With ES6, you can use shorthand property names which allow you to write something like this.

var s = 'abc';
var n = 1;
var o = { s, n }; // This is equivalent to { s: s, n: n }

In your case, prop = [1,2,3] was parsed as one shorthand property (s and n in the example above), but it was not a proper property name.

Solution 2:

Firefox has a different error message, which in my opinion is more useful:

SyntaxError: missing : after property id

That is, there is a missing :. As you say, you should use : instead of =.

To make it clear, "shorthand property" has no meaning in the ES6 spec. It's just some expression Chrome invented to help you noticing your error. It seems they failed.

snak's guess is that Chrome refers to a PropertyDefinition consisting of an IdentifierReference, used in an ObjectLiteral. Clearly prop = [1,2,3] is not an IdentifierReference, so it might make sense to complain about it. It would make even more sense to complain that it's not a PropertyDefinition in the much more common form of PropertyName : AssignmentExpression. Or MethodDefinition.