Lesson 12. New object literal syntax

 

After reading lesson 12, you will

  • Know how to use shorthand property names
  • Know how to use shorthand method names
  • Know how to use computed property names

I don’t think there’s anything as ubiquitous in JavaScript as the object literal. They’re everywhere. With a tool that’s used so frequently, any conveniences can have a huge net positive on productivity. Three syntactic additions to object literals introduced in ES2015 make them much more of a pleasure to read and write. You don’t gain new functionality, but having code that’s easy to read and write, especially when it comes to maintenance, is just as important a feature.

Consider this

Look at the following object literal. What parts seem redundant? If you were writing a JavaScript-aware string compression engine, what parts do you think you could safely remove while still being able to reconstruct the original object?

const redundant = {
  name: name,
  address: address,
  getStreet: function() { /* ... */ },
  getZip:    function() { /* ... */ },
  getCity:   function() { /* ... */ },
  getState:  function() { /* ... */ },
  getName:   function() { /* ... */ },
}

12.1. Shorthand property names

Before ES6 there were countless times when I would inevitably create an object literal that had a key or property whose name was the same as the variable I was assigning to it:

12.2. Shorthand method names

12.3. Computed property names

Summary