The destructuring assignment in ES6 allows us to locally scope fields within an object and
to declare which values will be used.
Example:
var sandwich = {
bread: "dutch crunch",
meat: "tuna",
cheese: "swiss",
toppings: ["lettuce", "tomato", "mustard"]
}
var {bread, meat} = sandwich;
console.log(bread, meat) ; // output will be dutch crunch tuna
in the above example the code pulls bread and meat out of the object and creates local variables for them.
Destructuring Assignment does not alter the value of Object
Example
var {bread, meat} = sandwich
bread = "garlic"
meat = "turkey"
console.log(bread) ; // output will be garlic
console.log(meat) // output will be turkey
console.log(sandwich.bread, sandwich.meat) ; // output will be dutch crunch tuna
destructure for incoming function arguments ?
In ES6 without destructuring incoming function arguments
var lordify = regularPerson => {
console.log(`${regularPerson.firstname} of Canterbury`);
}
var regularPerson = {
firstname: "Bill",
lastname: "Wilson"
}
lordify(regularPerson) ;
in destructuring Instead of using dot notation syntax to dig into objects, we can destructure the values that we need out of regularPerson
Example
var lordify = ({firstname}) => {
console.log(`${firstname} of Canterbury`);
}
lordify(regularPerson) ; // output will be Bill of Canterbury
destructured from arrays in ES6
var [firstResort] = ["Kirkwood", "Squaw", "Alpine"];
console.log(firstResort) ; output will be Kirkwood
Object Literal Enhancement
in ES6 Object literal enhancement is the opposite of destructuring. It is the process of restructuring or putting back together. With object literal enhancement,
we can grab variables from the global scope and turn them into an object with Object Literal Enhancement
Example:
var name = "Tallac"
var elevation = 9738
var funHike = {name,elevation}
console.log(funHike) ; //output will be {name: "Tallac", elevation: 9738}
in ES6 it’s no longer necessary to use the function keyword
Example
old Syntax Example
var skier = {
name: name,
sound: sound,
powderYell: function() {
var yell = this.sound.toUpperCase()
console.log(`${yell} ${yell} ${yell}!!!`)
},
speed: function(mph) {
this.speed = mph
console.log('speed:', mph)
}
}
In ES6 Syntax
const skier = {
name,
sound,
powderYell() {
let yell = this.sound.toUpperCase()
console.log(`${yell} ${yell} ${yell}!!!`)
},
speed(mph) {
this.speed = mph
console.log('speed:', mph)
}