JavaScript ES6 introduced destructuring, which allows you to extract values from arrays, or properties from objects. Destructuring allows for fewer lines of code which improves readability (and helps developers be lazy efficient).
Speaking of being efficient, check this out:
Visual Studio Code Shortcuts. ⌘D (command + d) — Add selection to… | by Hasibul Chowdhury | Medium
Hasibul Chowdhury ・ ・ 3 min read
Medium
Here is an example of a state object that might be passed down as props.
state = {
displayArray: [],
clicked: false,
searchKey: ""
}
In the past, I would have written the following to access the props:
let displayArray = props.displayArray
let clicked = props.clicked
let searchKey = props.searchKey
However, I can easily write those three lines as one line because I am accessing properties from the same object. In this case, the props
object.
Destructured:
let { displayArray, clicked, searchKey } = props;
Another Example:
<Card>
<img src={this.state.front ? this.props.pokemon.sprites.front : this.props.pokemon.sprites.back} alt=" "/>
<div className="header">{this.props.pokemon.name}</div>
</Card>
Or
let name = this.props.pokemon.name
let sprites = this.props.pokemon.sprites
<Card>
<img src={this.state.front ? sprites.front : sprites.back} alt=" "/>
<div className="header">{name}</div>
</Card>
Destructured:
let { name, sprites } = this.props.pokemon;
<Card>
<img src={this.state.front ? sprites.front : sprites.back} alt=" "/>
<div className="header">{name}</div>
</Card>
Sources:
Top comments (0)