By using destructuring assignment syntax we can unpack values from arrays, or properties from objects, into distinct variables:
const { firstName } = { firstName: 'Lydia' };
// ES5 version:
// var firstName = { firstName: 'Lydia' }.firstName;
console.log(firstName); // "Lydia"
Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property:
const { firstName: myName } = { firstName: 'Lydia' };
// ES5 version:
// var myName = { firstName: 'Lydia' }.firstName;
console.log(myName); // "Lydia"
console.log(firstName); // Uncaught ReferenceError: firstName is not defined
Therefore, firstName
does not exist as a variable, thus attempting to access its value will raise a ReferenceError
.
Note: Be aware of the global scope
properties:
const { name: myName } = { name: 'Lydia' };
console.log(myName); // "lydia"
console.log(name); // "" ----- Browser e.g. Chrome
console.log(name); // ReferenceError: name is not defined ----- NodeJS