[JavaScript Demo] Destructuring JavaScript Object Literal using ES6

This example demonstrates how to destructure JavaScript objects using ES6. Destructuring is new concept in ES6 JavaScript.

by Rahul Saraswat

HTML

<!-- Please press ctrl-shift-i to see output in browser console window. -->

JavaScript

var company = {
	name: 'Microsoft',
  location: 'Gurgaon'
};
//Old way to access object and its property values before ES6
console.log(`One of ${company.name}'s campuses is located in ${company.location}`);


var companyInfo = {
	companyName: "Microsoft",
  companyLocation: 'Gurgaon'
};
//new way to access object and its property values using ES6
var {companyName, companyLocation} = companyInfo;
console.log(`One of ${companyName}'s campuses is located in ${companyLocation}`);

//Important Note: property names inside object (line no.10 & 11) must be same as the variables names (line no. 14).

//If we want to assign a property to a variable with another name, for example : i want to assign companyInfo.companyName to a variable named 'cn', then

var {companyName: cn, companyLocation: cl} = companyInfo;
console.log(`One of ${cn}'s campuses is located in ${cl}`);