Close

JavaScript - ES6 Enhanced Object Literals

[Updated: Nov 13, 2018, Created: Nov 13, 2018]

In this tutorial we will go through object literal changes in JavaScript ES6.

Shorthand method names

Previously following function expressions were used in an object literal:

let task = {
    name: 'async task',
    start: function() { console.log("running " + this.name) }
};

console.log(task);
task.start();

In ES6 we can use method syntax (check out class syntax tutorial):

let task = {
    name: 'async task',
    start() { console.log("running " + this.name) }
};

console.log(task);
task.start();

Shorthand property names

Previously we could use external variable references to create object literate as:

let name = "Mike";
let phone = "111-111-111";
let person = { name: name, phone: phone, age: 30 };
console.log(person);

In ES6, if object's property has same name as the variable then:

let name = "Mike";
let phone = "111-111-111";
let person = { name, phone, age: 30 };
console.log(person);

Computed property names

ES6 also allows external variable values as object name (key) by using square brackets. We can also compute the property names by using some expression within square brackets.

let personId = "name";
let phone = "111-111-111";
let phoneType = "Cell";
let person = {
    [personId]: "John", [phoneType + "-Phone"]: phone };
console.log(person);

We can also use computed function/method name

let funcName = "doSomething";
let t = {
    [funcName]: function() {
        console.log('doing something');
    }
};

t.doSomething();

let funcName2 = "Display";
let t2 = {
    ["do" + funcName2]() { //using ES6 shorthand method syntax
        console.log('displaying');
    }
};

t2.doDisplay();

See Also