ariya.io About Talks Articles

ECMAScript 6 and Object Literal Property Value Shorthand

2 min read

Constructing an object using the literal syntax is something that is very familiar to every JavaScript developer, quite likely because this reminds everyone of JSON. While every object property needs to be either a key-value pair or getter/setter, this may change in the near future. Another syntactic sugar in the upcoming ECMAScript 6 is the object literal property value shorthand.

Consider the following ECMAScript 5 fragment:

function createMonster(name, power) {
  return { type: 'Monster', name: name, power: power };
}
function createWitch(name) {
  return { type: 'Witch', name: name };
}

With the new shorthand form, this can be rewritten as the following code:

function createMonster(name, power) {
  return { type: 'Monster', name, power };
}
function createWitch(name) {
  return { type: 'Witch', name };
}

As you can see, this works because the property value has the same name as the property identifier. This a new addition to the syntax of Object Initialiser (section 11.1.5) in the latest ECMAScript 6 draft Rev 13. Of course, just like the limitations set from ECMAScript 3, you can’t use a reserved word as your property name.

What about real-world code which can use the shorthand notation? Somewhere in Backbone.js, we should be able to use the following form instead of its longer one:

route: function(route, callback) {
  this.handlers.unshift({route, callback});
},

For improved readibility, many times we use temporary variables before constructing an object out of the properties. As another example, a piece of code QUnit may have the following simplified syntax:

test = new Test({nameHtml, testName, expected, async,
  callback,module: config.currentModule,
  moduleTestEnvironment: config.currentModuleTestEnvironment,
  stack: sourceFromStacktrace(2)
});

Such a shorthand won’t dramatically change your code, it only makes everything a little bit sweeter!

Addendum. While the literal shorthand is useful on its own, in many cases it would be more frequently encountered as it is combined with object pattern (see my previous post on ECMAScript 6 destructuring). Thus, the following code fragment:

books.forEach(function ({title: title, author: author}) {
  console.log(title, 'is written by', author);
});

turns into something like this one:

books.forEach(function ({title, author}) {
  console.log(title, 'is written by', author);
});

As you can see, such a symmetry is well suited for this case.

Related posts:

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook