Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is JavaScript shorthand property? [duplicate]

Tags:

javascript

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?

like image 326
exebook Avatar asked Aug 15 '16 01:08

exebook


People also ask

What is shorthand property in JavaScript?

With Shorthand Properties, whenever you have a variable which is the same name as a property on an object, when constructing the object, you can omit the property name. What that means is that code that used to look like this, function formatMessage (name, id, avatar) {

What is shorthand property?

Shorthand properties are CSS properties that let you set the values of multiple other CSS properties simultaneously. Using a shorthand property, you can write more concise (and often more readable) style sheets, saving time and energy.

Which property is used to shorthand property?

CSS Border - Shorthand Property The border property is a shorthand property for the following individual border properties: border-width.

Which property is used as the shorthand padding properties?

An element's padding is the space between its content and its border. The padding property is a shorthand property for: padding-top. padding-right.


2 Answers

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.

like image 95
snak Avatar answered Nov 15 '22 10:11

snak


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.

like image 39
Oriol Avatar answered Nov 15 '22 08:11

Oriol