Javascript - Object Literal with variables

Introduction

To declare object literals using variables we have to use the following coding pattern:

var price = 4.20, count = 20; 
var myOrder = { 
   price: price, 
   count: count 
}; 

console.log(myOrder); 

Using ES6 we can rewrite the code above as:

const price = 4.20, count = 20; 
const myOrder = { 
   price, 
   count 
}; 

console.log(myOrder); 

Here, we can just list the field once.

The object literal in ES6 is smart enough to interpret that we want a field called price and want the context data set to the value of the variable called price.

Related Topic