ES6: 3 new ways of defining object properties in JavaScript

Repetitive boilerplate code is something that haunts most developers to some degree. It’s like an itch that can’t be scratched. It drags you away from the flow, it messes up your code, and it blurs away the important parts.

What I love about ES6 is that it takes care of a lot of the annoying repetitive code, leaving you with a clear codebase focusing on the important parts.

I've already talked about destructuring, the syntax spread and new ways of declaring variables using let and const.

In this post, we'll continue to look at ES6 and its features by looking at 3 new ways of defining properties during object initialization.

Let’s dive in!

The property shorthand

The property shorthand is all about removing duplications.

Say we got two variables — name and age.

const name = "Luke";  
const age = 24;  

Now, if we would like to assign these variables to object properties with identical namings, we would have to repeat it both for the property to give the name and the value to refer to our variable.

{
  name: name,
  age: age
}

This repetition of name and age feels a bit unnecessary, right? Well, this is what ES6 has taken care of with the property shorthand.

{
  name,
  age
}

By simply replacing name: name with name, JavaScript understands that you want to take the value name and assign it to a property with the same name as the variable.

Method properties

Another popular usage of an object is to define methods. This is done by assigning functions to the object properties.

To keep it simple, let’s create two getter functions for fetching name and age.

{
  getName: function() { return "Luke" },
  getAge: function() {return 24 }
}

Again, this solution becomes quite verbose.

Well, no more. In ES6 we can use syntactical sugar to make our method definitions way more concise.

{
  getName() { return "Luke" },
  getAge() {return 24 }
}

Computing property names

The last thing we're going to look at is the possibility of computing your property names by evaluating an expression.

Say we got a function - getLo - that simply returns the string ”lo”.

var getLo = () => "lo"  

Now let’s create our property name by combining the string “hel” and the execution of getLo(), which results in the string hello.

In the old days this would be solved in two steps — first initializing the object, then use the square brackets to create a property in the object.

var obj = {};  
obj[ "hel" + getLo() ] = "world";  

This is not too bad, but we can do even better with ES6 by moving the square brackets with our expression directly into the object initialization.

let obj2 = {  
  [ "hel" + getLo() ]: "world"
}

There you go — 3 new ways of defining properties in JavaScript.

Enjoyed the post?

If you don't want to miss future posts, make sure to subscribe