Array and Object Destructuring in JavaScript
By: Vikash Kumar Jha
Tags: ES6, Destructuring Syntax, Arrays, JavaScript

One of the most interesting features that ES6 added to JavaScript was object and array destructuring. With destructuring we can take part of an array or an object very easily. Let’s understand by taking up a few examples

Array Destructuring

const alphabets = ['A','B','C','D','E','F']

const numbers = ['1','2','3','4','5','6']

Now if we have to pick the first two items from the alphabets array. The conventional way would be,

const a = alphabets[0]

const b = alphabets[1] console.log(a)

//expected output : A console.log(b)

//expected output : B

It is very obvious that the above approach is very clunky and there is a much easier way of doing this. Using the spread operator syntax,

const [a,b] = alphabets console.log(a)

//expected output : A console.log(b)

//expected output : B

The question arises is how exactly does it work??

So the idea behind destructuring is we take the array (alphabets array in our case) we want to destructure and put that on the right side of the equals sign. On the left side of the equals sign we take the number of variables we want to pull out of the array and enclose that between brackets ([]). The key point to notice here is the elements inside the array on the left side follow the same order as of the array on the right side. That is how the first element a gets assigned the first element ‘A’ and the second element b gets the second element ‘B’.

Adding a third element c on the left hand side will result in

const [a,b,c] = alphabets console.log(a)

//expected output : A console.log(b)

//expected output : B console.log(c)

//expected output : C

If we want to skip any element let’s say ‘B’ for example, we can

const [a,,c] = alphabets console.log(a)

//expected output : A console.log(c)

//expected output : C

Use of spread operators

If we want to take rest of the elements from the alphabets into a separate array, we can simply do this using the spread operator.

const [a,,c, ...rest] = alphabets console.log(a)

//expected output : A console.log(c)

//expected output : C console.log(rest)

//expected output: ['D','E','F']

The another really powerful thing with destructuring and spread operators is we can use it to combine two arrays as well.

const newArray = [...alphabets, ...numbers] console.log(newArray)

//expected output: ['A','B','C','D','E','F','1','2','3','4','5','6']

Array Destructuring with functions

The array destructuring is incredibly useful while dealing with functions when we are returning more than one parameter from a function.

Let’s create a simple function first which calculates sum and multiplication of two numbers.

function sumAndMultiply(a,b){

return [a+b, a*b]

} const result = sumAndMultiply(2,3)

console.log(result)

//expected output: [5,6]

Using array destructuring,

const [sum, mul] = sumAndMultiply(2,3) console.log(sum)

//expected output: 5 console.log(mul)

//expected output: 6

Something handy that we can do we this array destructuring is that we can set default values. Let’s say the function can also return division and if it doesn't we will simply set some value as No division

const [sum, mul, div = 'No division'] = sumAndMultiply(2,3) console.log(sum)

//expected output: 5 console.log(mul)

//expected output: 6 console.log(div)

//expected output: 'No division'

But if we change the sumAndMultiply function to return the division also , The output will be as

function sumAndMultiply(a,b){

return [a+b, a*b, a/b]

} const [sum, mul, div = 'No division'] = sumAndMultiply(2,3) console.log(sum)

//expected output: 5 console.log(mul)

//expected output: 6 console.log(div)

//expected output: 0.6666666666666

Object Destructuring

The real power of destructuring comes with objects so let’s jump in and look over object destructuring.

const personOne = {

name : 'Vikash',

age : 25,

address : {

city : 'some city',

state : 'some state'

}

}

When we want to destructure an object it works very similarly to an array. Let’s say we want to get the name and age of the object. So since we are destructuring an object we will be using {} instead of []

const {name , age} = personOne console.log(name)

//expected output: Vikash console.log(age)

//expected output: 25

The object destructuring works exactly the same as arrays but instead of based on position it is actually based the name of the key. So the name variable inside the {} is same as the name key in the personOne object and same goes for age. They need to match.

But what if we want to use a different name ?

we can easily do that by simply giving the actual name inside the curly brace and then after that we put a colon and then the variable name we want.

const {name:firstName, age} = personOne console.log(firstName);

//expected output: Vikash

what the above code is doing is taking the name property from the personOne object and mapping it to firstName variable that we are creating.

We can even use default values in object destructuring the same way we were using it with array destructuring . Let’s say we want to get something that the personOne object doesn’t already have. We will be deleting the name property from the personOne object and try to access that along with a new property favoriteFood using default values.

const personOne = {

age : 25,

address : {

city : 'some city',

state : 'some state'

}

} const {name:firstName = 'John', age, favouriteFood='No food present'} = personOne console.log(firstName);

//expected output: John console.log(favouriteFood)

//expected output: No food present

But if we have both the properties in place, we get the actual values despite of any value set as default.

const personOne = {

name : 'Vikash',

age : 25,

favouriteFood : 'rice'

address : {

city : 'some city',

state : 'some state'

}

} const {name:firstName = 'John', age, favouriteFood='No food present'} = personOne console.log(firstName);

//expected output: Vikash console.log(favouriteFood)

//expected output: rice

Use of spread operators

Just like the array deconstructing, we can use the spread operator here as well.

const {name:firstName,favouriteFood, ...rest} = personOne console.log(firstName);

//expected output: Vikash console.log(favouriteFood)

//expected output: rice console.log(rest)

//expected output: {

age : 25,

address : {

city : 'some city',

state : 'some state'

}

}

Also something that really nice about object destructuring is we can actually destruct our nested objects.

const {name : firstName, address : {city} } = personOne console.log(firstName);

//expected output: Vikash console.log(city);

//expected output: some city

Another thing we can do with destructuring is that we can combine two different objects. Let’s take two different objects

const personOne = {

name : 'Vikash',

age : 25,

address : {

city : 'some city',

state : 'some state'

}

} const personTwo = {

age : 32,

favouriteFood : 'rice'

} const personThree = {...personOne , ...personTwo} console.log(personThree)

//expected output: {

name : 'Vikash',

age : 32,

favouriteFood : 'rice',

address : {

city : 'some city',

state : 'some state'

}

}

Let’s try to understand what happened in the above example. It says that take

everything that is present in personOne is put into the personThree object and then again take everything from the personTwo and put into personThree but overwrite anything that was already in personOne.

In the console we get the name ‘Vikash’ which was present in personOne. We get the age 32 because that gets overwritten by personTwo. The favouriteFood shows ‘rice’ because it was only present in personTwo and the address is same as the address in personOne because it’s not present in personTwo.

Object destructing with functions

Another important and useful part of object destructuring is the ability to use it inside functions and arguments. We will be using the same object personOne here

const personOne = {

name : 'Vikash',

age : 25,

address : {

city : 'some city',

state : 'some state'

}

}

Let’s create a function and see some of the use cases.

function printUser(user){

console.log(user);

} printUser(personOne) //expected output:{

name : 'Vikash',

age : 25,

address : {

city : 'some city',

state : 'some state'

}

}

what if we want to print only the name and the age inside of the printUser function. We can use destructuring in the function parameters like this

function printUser({name, age}){

console.log('Name is: ${name}. Age is: ${age}');

} printUser(personOne) //expected output: Name is Vikash. Age is 25

we can also set defaults like

function printUser({name, age, favouriteFood='No food'}){

console.log('Name is: ${name}. Food is ${favouriteFood}');

} printUser(personOne) //expected output: Name is Vikash. Food is No food.

And if we add the favouriteFood property to our object , the default value doesn’t matter at all.