5New Object Features

In this chapter you'll learn about the new object features in ES2015+, from features that help you write less repetitive or more concise code to ones that let you do things you couldn't do before.

COMPUTED PROPERTY NAMES

In ES5, if you wanted to create an object with a property whose name came from a variable, you had to first create the object, then add the property to it as a separate operation, like this:

var name = "answer";
var obj = {};
obj[name] = 42;
console.log(obj); // {answer: 42}

That's a bit awkward, so ES2015 added computed property names, which use square brackets ( []), just like the square brackets used in the preceding code, in the property definition itself:

var name = "answer";
var obj = {
    [name]: 42
};
console.log(obj); // {answer: 42}

(I've used var there to emphasize this isn't related to let, but I'll go back to using let and const now.)

The brackets in the property definition work just like the brackets you've always used when getting/setting property values. That means you can use ...

Get JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.