bradxr
8/8/2018 - 2:58 PM

Destructuring Assignment

Allows you to locally scope fields within an object and to declare which values will be used.

Src - “Learning React by Alex Banks and Eve Porcello (O’Reilly). Copyright 2017 Alex Banks, Eve Porcello, 978-1-491-95462-1.”

// 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