Created
January 25, 2019 19:53
-
-
Save gil00pita/bd3f7bdddf3ccd6f11cf499f6c203b09 to your computer and use it in GitHub Desktop.
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment