Enhanced object literals in ES6
July 18, 2017 1 Comment
ES6 comes with a couple of syntactic enhancements regarding object literals. These enhancements do not add new functionality to JavaScript. Instead, they are syntactic sugar that make it possible to write a little less code.
Here’s a simple example of a “normal” JSON object returned without these enhancements:
function makePerson(name, yearOfBirth) { return { name: name, yearOfBirth: yearOfBirth, age: function() { let currentYear = new Date().getFullYear() return currentYear - this.yearOfBirth }, sayHello: function(periodOfDay) { return `Good ${periodOfDay}, ${this.name}!` } } }
This is how we invoke the function:
let person = makePerson('Jane', 1980) person.name person.age() person.sayHello('morning')
We return an object with two properties and two functions. One function has no parameters, while the other one has a single input parameter. With ES6 we can make this code shorter by following these rules:
- If the key and the value have identical names, like name: name above, then it’s enough to write the key
- We can leave out the “function” keyword and the colon for functions. It’s enough to keep the parenthesis and any function parameters
The following shows the slightly reduced object literal by applying the above rules:
function makePerson(name, yearOfBirth) { return { name, yearOfBirth, age() { let currentYear = new Date().getFullYear() return currentYear - this.yearOfBirth }, sayHello(periodOfDay) { return `Good ${periodOfDay}, ${this.name}!` } } }
Note how we only need to state “name” and “yearOfBirth” once. Keep in mind that it is equivalent to writing name: name and yearOfBirth: yearOfBirth, so we’re not somehow creating a key with no value. The code example which uses makePerson still works as before.
View all posts related to JavaScript here.
Thanks. It is really useful feature .