Destructuring objects and arrays in JS
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Destructuring is a convenient way of creating new variables by extracting some values from data stored in objects or arrays.
To name a few use cases, destructuring can be used to destructure function parameters or this.props
in React projects for instance.
Explanation with sample code
Object
Let's consider the following object for all the samples:
const person = {
firstName: "Nick",
lastName: "Anderson",
age: 35,
sex: "M"
}
Without destructuring
With destructuring, all in one line:
Note : In const { age } = person
, the brackets after const keyword are not used to declare an object nor a block but is the destructuring syntax.
Function parameters
Destructuring is often used to destructure objects parameters in functions.
Without destructuring
In destructuring the object parameter person
, we get a more concise function:
Destructuring is even more pleasant to use with arrow functions:
Array
Lets consider the following array:
const myArray = ["a", "b", "c"];
Without destructuring
With destructuring