Skip to content

Object property shorthand

When assigning a variable to an object property, if the variable name is equal to the property name, you can do the following:

1
2
3
const x = 10;
const myObj = { x };
console.log(myObj.x) // 10

Explanation

Usually (pre-ES2015) when you declare a new object literal and want to use variables as object properties values, you would write this kind of code:

const x = 10;
const y = 20;

const myObj = {
  x: x, // assigning x variable value to myObj.x
  y: y // assigning y variable value to myObj.y
};

console.log(myObj.x) // 10
console.log(myObj.y) // 20

As you can see, this is quite repetitive because the properties name of myObj are the same as the variable names you want to assign to those properties.

With ES2015, when the variable name is the same as the property name, you can do this shorthand:

const x = 10;
const y = 20;

const myObj = {
  x,
  y
};

console.log(myObj.x) // 10
console.log(myObj.y) // 20

External resources