One of the most useful new syntax introduced in ES6, destructuring assignment is simply copying a part of object or array and put them into named variables. A quick example:
const developer = {
firstName: 'Nathan',
lastName: 'Sebhastian',
developer: true,
age: 25,
}
//destructure developer object
const { firstName, lastName } = developer;
console.log(firstName); // returns 'Nathan'
console.log(lastName); // returns 'Sebhastian'
console.log(developer); // returns the object
/*
* As you can see, we assigned firstName and lastName from developer object into new variable firstName and lastName.
* Now what if you want to put firstName into a new variable called name?
*/
const { firstName:name } = developer;
console.log(name); // returns 'Nathan'
//Destructuring also works on arrays, only it uses index instead of object keys:
const numbers = [1,2,3,4,5];
const [one, two] = numbers; // one = 1, two = 2
//You can skip some index from destructuring by passing it with ,:
const [one, two, , four] = numbers; // one = 1, two = 2, four = 4
//Mostly used in destructuring state in methods, for example:
reactFunction = () => {
const { name, email } = this.state;
};
//Or in functional stateless component, consider the example from previous chapter:
const HelloWorld = (props) => {
return <h1>{props.hello}</h1>;
}
//We can simply destructure the parameter immediately:
const HelloWorld = ({ hello }) => {
return <h1>{hello}</h1>;
}