Enhanced object literals in ES6

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Enhanced object literals in ES6

  1. peyman says:

    Thanks. It is really useful feature .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: