Destructuring in ES6 deals with take either an Array or an Object, and get or set variables based on the elements of that Array or Object.
First lets talk about the syntax. To destructure something in ES6 you put … in front of the Array or Object you are wanting to pull apart.
[javascript]
//Array example
var numbers = [1,2,3];
console.log(numbers) //logs [1,2,3]
console.log(…numbers) //logs 1, 2, 3
[/javascript]
In the second example, … has precedence so the [1,2,3] is first split into 3 separate values, then console.log(…numbers) becomes console.log(1,2,3).
That is how we easily get at them, here is an example of the setting pattern.
[javascript]
function getAddress() {
return {city: ‘St. Louis’, state: ‘Missouri’, country: ‘USA’}
}
let {city, state, country} = getAddress();
console.log(city, state, country) //logs ‘St. Louis’, ‘Missouri’, ‘USA’
[/javascript]
This works because we know that getAddress will return a value that is matching what we have in curly braces on the left. So we know getAddress will return a city, so we call it city in the let.
We can also alias variables in our let statement, in the example below, we tell javascript to map the value of getAddress().city to cityAlias locally.
[javascript]
let {city: cityAlias, state, country} = getAddress();
console.log(cityAlias, state, country) //logs ‘St. Louis’, ‘Missouri’, ‘USA’
console.log(city) //Reference error because city is not defined
[/javascript]
You can use this pattern anywhere and it may be more readable. Here is an example in a function call.
[javascript]
function printUserAddress({city, state, country}) {
console.log(city, state, country);
}
printUserAddress(getAddres());
////logs ‘St. Louis’, ‘Missouri’, ‘USA’
[/javascript]
You can also set default values to deal with cases where the object passed in does not have the value you are trying to get.
[javascript]
function printUserAddress({city, state, country, zip=’N/A’}) {
console.log(city, state, country, zip);
}
printUserAddress(getAddres());
//logs ‘St. Louis’, ‘Missouri’, ‘USA’, ‘N/A’
[/javascript]
Under the hood here are the rules.
{} on the left means that the object on the right MUST have the properties, or it will be an error
[javascript]
function printUserAddress({city, state, country, zip}) {
console.log(city, state, country, zip);
}
printUserAddress(getAddres());
//throws b/c zip is not in the object
[/javascript]
You can bypass the throw by adding a ? in front of the attribute which may or may not be defined
[javascript]
//zip is optional
function printUserAddress({city, state, country, ?zip}) {
console.log(city, state, country, zip);
}
printUserAddress(getAddres());
//logs ‘St. Louis’, ‘Missouri’, ‘USA’, ‘undefined’
//entire object is optional
function printUserAddress(?{city, state, country, zip}) {
console.log(city, state, country, zip);
}
printUserAddress(getAddres());
//logs ‘St. Louis’, ‘Missouri’, ‘USA’, ‘undefined’
[/javascript]