// consider the below object, it has 4 keys but we only want to use the values of two
// we can scope bread and meat to be used locally
var sandwich = {
bread: "dutch crunch",
meat: "tuna",
cheese: "swiss",
toppings: ["lettuce", "tomato", "mustard"]
}
// the code below pulls bread and meat out of the object and creates local variables for them.
var {bread, meat} = sandwich
console.log(bread, meat) // dutch crunch tuna
// the bread and meat variables can also be changed
bread = "garlic"
meat = "turkey"
console.log(bread) // garlic
console.log(meat) // turkey
// object properties remain unchanged due to scope of bread and meat variables
console.log(sandwich.bread, sandwich.meat) // dutch crunch tuna
// we can also DESTRUCTURE INCOMING FUNCTION ARGUMENTS.
// consider this function that would log a person's name as a lord
var lordify = regularPerson => {
console.log(`${regularPerson.firstName} of Canterbury`)
}
var regularPerson = {
firstName: "Bill",
lastName: "Wilson"
}
lordify(regularPerson) // Bill of Canterbury
// instead of using dot notation, we can destructure the values we need, as follows
var lordify = ({firstName}) => {
console.log(`${firstName} of Canterbury`)
}
lordify(regularPerson) // Bill of Canterbury
//DESTRUCTURING VALUES FROM ARRAYS
var [firstResort] = ["Kirkwood", "Squaw", "Alpine"]
console.log(firstResort) // Kirkwood
// we can pass over values by using commas
var [,,thirdResort] = ["Kirkwood", "Squaw", "Alpine"]
console.log(thirdResort) // Alpine