Array/Object Destructuring in JavaScript

Photo by Andrew Neel on Unsplash

Array/Object Destructuring in JavaScript

Destructuring in js refers to the unpacking of values from arrays and properties from objects into distinct variables.

Now, what does this mean?

Let's say we have an array of two elements and we want to store the values in two variables. Conventionally we would go with this approach.

const arr = [1, 3];
const a = arr[0];
const b = arr[1];

OR if we have an object and we want to get the properties from the array we will access the values using dot(.) operator

const obj = {
  name: "Naruto",
  power: "Rasengan",
};

const name = obj.name;
const power = obj.power;

Javascript introduced the concept of destructuring in ES6, which makes it very easy to extract data from arrays/objects and store them in distinct variables. For the above problems, we will use the following approaches.

For array


const arr = [1, 3];
const [a,b] = arr;

/*
a = 1
b = 3
*/

For object


const obj = {
  name: "Naruto",
  power: "Rasengan",
};

const { name, power } = obj;
/*
name -> Naruto
power -> Rasengan
*/

Default values

We can also assign some default values if the value we are trying to extract does not exist.

const [a, b, c = 1] = [1,3];

const { name, power,age=0 } = {name: "Naruto",
  power: "Rasengan"};

In the above example the value of c will be 1 as the array only has 2 elements and c is trying to extract 3rd element.

AND age will be 0 as age is not present in the object which is being destructured.