Object Literals Using Object Property Shorthand

How the object property shorthand in JavaScript makes our code concise.

Let’s imagine we are writing a program that required us to model some data about some clothing. To do this we may use an object. Before ES6 if we were using an object literal then we would model the data in the following way:

function createWardrobe() {
  var hat = 1;
  var shorts = 5;
  var jumper = 8;
  var socks = 2;
  var myWardrobe = {
    hat: hat,
    shorts: shorts,
    jumper: jumper,
    socks: socks,
  };

  return myWardrobe;
}
console.log(createWardrobe());
//Returns ---> {hat: 1, shorts: 5, jumper: 8, socks: 2}

In the code above, we declare a function called createWardrobe. Inside of the function, we declare variables for the wardrobe items which are initialised with values. An object literal is then created and stored in the variable myWardrobe. The keys are set in the object literal and the values are the variables from the wardrobe items at the start of the function. The object is then returned. When the function runs we can see from the console log the object with the corresponding values.

When ES6 was created object property shorthand was introduced. Object property shorthand enables us to simply pass in the name of the key as opposed to repeating the name and the key.

//PRE ES6var myObject = {
  myKeyName: myKeyName
};
//ES6 Object property shorthand
var myObject = {
  myKeyName
};

Nothing has changed in the way the code works under the hood but the shorthand helps us to write less code! It is what is referred to as syntactic sugar. Let’s take the createWardrobe function and look at it again but this time using the object property shorthand.

const createWardrobe = () => {
  let hat = 1;
  let shorts = 5;
  let jumper = 8;
  let socks = 2;
  let myWardrobe = {
    hat,
    shorts,
    jumper,
    socks,
  };

  return myWardrobe;
};
console.log(createWardrobe());
//Returns ---> {hat: 1, shorts: 5, jumper: 8, socks: 2}

The output from the console log is the same but the code itself is simpler!

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics