Back
Close

Destructuring objects and arrays in JS

ma[CG]yver
12.6K views

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

Useful resources

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants