Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ES6 object shorthand notation be combined with regular object notation?

With ES6 we can now utilize object shorthand notation for creating objects...

var a = 1, b = 2, c = 3;
var obj = { a, b, c };

Is it possible to combine shorthand notation with regular notation?

In other words, is the following legit?

var obj = {a, b, c, d: 'foo'};

And if so, are there any gotchas I should be aware of?

like image 523
sfletche Avatar asked Mar 25 '16 00:03

sfletche


People also ask

What is object shorthand in JavaScript?

Object property shorthand enables us to simply pass in the name of the key as opposed to repeating the name and the key.

What is the correct syntax for declaring an object literal?

Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.

Is everything in JavaScript an object?

Nearly everything in JavaScript is an object other than six things that are not objects which are — null , undefined , strings, numbers, boolean, and symbols. These are called primitive values or primitive types.

How to initialize list of objects in JavaScript?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation).


2 Answers

Is it possible to combine shorthand notation with regular notation?

Yes. A property definition can be any of the following:

PropertyDefinition :
    IdentifierReference
    CoverInitializedName
    PropertyName : AssignmentExpression
    MethodDefinition

Source: ECMAScript 2015 Language Specification

And if so, are there any gotchas I should be aware of?

Nope.

like image 96
Felix Kling Avatar answered Sep 28 '22 05:09

Felix Kling


According to Babel yes

See transpiled code results

Babel translates this

var a = 1, b = 2, c = 3;
var obj = {a, b, c, d: 'foo'};

into this in es5

var a = 1,
b = 2,
c = 3;

var obj = { a: a, b: b, c: c, d: 'foo' };

Also found a github repo by Luke Hoban that shows mixed objects being created

like image 28
konkked Avatar answered Sep 28 '22 04:09

konkked