Destructuring really means grabbing things that are inside of objects and arrays directly. We’ll
just be worrying about objects to begin with, and dealing with arrays later on.
Say for example we have some data about SuperHi in a company
variable:
const company = {
name: 'SuperHi',
location: 'New York',
ceo: 'Rik Lomas',
founded: 2013,
}
We could make some extra variables from our company like this:
const name = company.name
const location = company.location
const ceo = company.ceo
See the repetition there? With destructuring we can assign those three variables in one go:
const {name, location, ceo} = company
We could write a function that gives us back some company info:
const company = {
name: 'SuperHi',
location: 'New York',
ceo: 'Rik Lomas',
founded: 2013,
}
And then use the data like this:
const companyInfo = company => {
return `${company.name} is based in ${company.location}`
}
companyInfo(company)
With destructing we can instead grab the data we want right inside of the function arguments:
const companyInfo = ({name, location}) => {
return `${name} is based in ${location}`
}
companyInfo(company)
This is useful as it neatens up code and repetition.
Destructuring is a bit confusing at first but once you’re exposed to it it will click into place.
We’ll be using it to grab props
inside of our React components to neaten things up.