Destructuring

Pranay Chauhan
Last Updated: May 13, 2022

Introduction

JavaScript(js) is a lightweight, interpreted, object-oriented language with first-class functions and is best known as the scripting language for Web pages. Still, it’s used in many non-browser environments as well.

In javascript, the two most used data structures are Objects and Arrays. 

  • Arrays allow us to combine data items into an ordered list.
  • Objects are a single entity that stores data items by key.

How can we access the individual elements of the object or array?

This is where the technique of destructuring these data structures comes into play.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into many variables, making it more convenient to work with them.

Destructuring is very helpful when working with complex functions that have a lot of parameters, default values, and so on.

In this article, we will further have a look at how to do array destructuring and object destructuring.

Object Destructuring

The destructuring assignment also works with objects.

The basic syntax is:

let {var1, var2} = {var1:…, var2:…}

We should have an existing object on the right side that we want to split into individual elements. The left side has an object-like “pattern” for every property.

For instance:

let object1 = {
 title: "CodingNinjas",
 width: 100,
 height: 200
};

let {title, width, height} = object1;

alert(title);  // CodingNinjas
alert(width);  // 100
alert(height); // 200

All the properties of options are assigned to the corresponding variables.

The order does not matter. This works too:

// changed the order in let {...}
let {height, width, title} = { title: "CodingNinjas", height: 200, width: 100 }

The pattern on the left side can be more complex.

If we want to assign a property to a variable with a different name, make options.width goes into the variable named w, then we can set the variable name using a colon:

let object1 = {
 title: "Menu",
 width: 100,
 height: 200
};

// { sourceProperty: targetVariable }
let {width: w, height: h, title} = object1;

// width -> w
// height -> h
// title -> title

alert(title);  // CodingNinjas
alert(w);      // 100
alert(h);      // 200

 

The colon shows “what: goes where.”; then, In the example above, the property width goes to w, property height goes to h, and the title is assigned to the variable of the same name.

For any of the missing properties we can set default values using "=", like this:

let object1 = {
 title: "CodingNinjas"
};

let {width = 100, height = 200, title} = object1;

alert(title);  // CodingNinjas
alert(width);  // 100
alert(height); // 200

 

We also can combine both the colon and equality:

let object1= {
 title: "CodingNinjas"
};

let {width: w = 100, height: h = 200, title} = object1;

alert(title);  // CodingNinjas
alert(w);      // 100
alert(h);      // 200

 

If we have a complex object which has many properties, we can also extract only what we need by using the key name to access it:

let object1 = {
 title: "CodingNinjas",
 width: 100,
 height: 200
};

// only extract title as a variable
let { title } = object1;

alert(title); // CodingNinjas

The rest pattern “…”

If a complex object has more properties than the number of variables. 

Can we take some of the properties and then assign the “rest” somewhere?

We can use the rest pattern as shown below. It is not supported by some older browsers but works in modern ones.

It looks like this:

let object1 = {
 title: "CodingNinjas",
 height: 200,
 width: 100
};

// title = property named title
// rest = object with the rest of properties
let {title, ...rest} = object1;

// now title="Menu", rest={height: 200, width: 100}
alert(rest.height);  // 200
alert(rest.width);   // 100

Array Destructuring


Here is an example of how an array is destructured into variables:

// we have an array as shown below
let arr = ["Coding", "Ninjas"];

// destructuring assignment sets firstWord = arr[0] and secondWord = arr[1]
let [firstWord, secondWord] = arr;

alert(firstWord);
alert(secondWord);

 

We can work with variables declared by us instead of array members.

This technique looks great when combined with split or other array-returning methods:

let [firstWord, secondWord] = "Coding Ninjas".split(" ");

alert(firstWord);
alert(secondWord);

From the implementation, we can see that the syntax is simple. There are several particular details, though. Let’s see more examples to understand it better.

Key Points

Ignore elements using commas

Unwanted elements of the array can be skipped via an extra comma:

// second and last element is not needed
let [firstWord, , title] = ["Coding", "Ninjas", "Javascript", "Destructuring"];

alert( title ); // Javascript

 

In the above implementation, we can observe that the second element of the array is skipped, the third one is assigned to the title, and the rest of the array items are also skipped because there are no variables for it.

Assign any value on the left side to any data structure on the right side.

We can have any data structure already defined, and we can assign any value on the right side to the members of the data structure that are destructured on the left-hand side.

We can use any “assignable” on the left side.

For instance, an object property:

let object1 = {};
[object1.name, object1.surname] = "Coding Ninjas".split(' ');

alert(object1.name); // Coding
alert(object2.surname); // Ninjas

Looping with .entries()

We can use it with destructuring to loop over keys-and-values of an object:

let user = {
 name: "Pranay",
 age: 19
};

for (let [k, v] of Object.entries(user)) {
 alert(`${k}:${v}`); // name:Pranay, then age:19
}

The code shown above can also be implemented using Maps in javascript. The Map implementation is more simple to implement having a shorter code. We can iterate through all the entries in the map by generic destructuring within the “for” loop.

The code implementation for a Map will be:

let user = new Map();
user.set("name", "Pranay");
user.set("age", "19");

for (let [key, value] of user) {
 alert(`${key}:${value}`); // name:John, then age:30
}

Swap variables trick

We can swap variables using the destructuring assignment.

let guest = "John";
let admin = "Pete";

[guest, admin] = [admin, guest];

alert(`${guest} ${admin}`); //successfully swapped!


We create a temporary variable array of two variables and we destructure them at the same time to allow swapping of two variables, we can also swap more than two variables by this technique.

The rest ‘...’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

let [firstWord, secondWord] = ["Coding", "Ninjas", "Javascript", "Destructuring"];

alert(firstWord); // Coding
alert(secondWord); // Ninjas

 

Other items aren't assigned anywhere.

If we’d also like to gather all that follows – we can add one more parameter that gets “the rest” using three dots "...":

let [firstWord, secondWord, ...rest] = ["Coding", "Ninjas", "Javascript", "Destructuring"];

alert(rest[0]); // Javascript
alert(rest[1]); // Destructuring

 

Here rest is the array of the remaining elements of the array. We are allowed to use any other variable name instead of rest. We need to make sure that there are three dots before the variable’s name, and it goes as the last value in the destructuring assignment.

Default values

If the given array is shorter than the list of variables at the left, there’ll be no errors. Missing values are considered undefined:

let [firstWord, secondWord] = [];

alert(firstWord); // undefined
alert(secondWord); // undefined

 

To define default values to the missing values, we can provide it using =:

let [name = "defaultValue1", surname = "Ninjas"] = ["Coding"];

alert(name);    // Coding (from array)
alert(surname); // Ninjas (default used)

Nested Destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

The code below object1 has another nested object in the property size and an array in the property items. The structure at the left side of the assignment should have the same structure to extract values from them:

let object1 = {
 size: {
   width: 100,
   height: 200
 },
 items: ["Item1", "Item2"],
 extra: true
};

let {
 size: {
   width,
   height
 },
 items: [item1, item2], // assign items here
 title = "CodingNinjas" // not present in the object (default value is used)
} = object1;

alert(title);  // CodingNinjas
alert(width);  // 100
alert(height); // 200
alert(item1);  // Item1
alert(item2);  // Item2

All the properties of the “object1” object are assigned to the corresponding variables except extra. And in the alert, we can see that we have width, height, item1, item2, and title from the default value. Note that we have not defined the variables for size and items as we take their content.

Smart function parameters

Many times in our code, we come across functions that have many parameters, and most of that is optional. Consider a function that creates a menu. It may have a width, a height, a title, items list and so on.

Below is the bad way of implementation to write such function:

function showMenu(title = "Untitled", width = 200, height = 100, items = []) {
 // ...
}

The common problem a developer comes across is to remember the order of arguments. Usually, we take help from an IDE. But another problem is how to call a function when most of the parameters are fine by default.

We can do it naively as shown below:

// undefined where default values are fine
showMenu("My Menu", undefined, undefined, ["Item1", "Item2"])

This implementation is ugly. And the code becomes unreadable when we deal with more parameters.

We use destructuring to solve this problem.

We can pass parameters as an object, and the function immediately destructurizes them into 

Variables:

As shown in the below implementation, we can pass the parameters as an object, and the function destructurises them into individual variables.

let object1 = {
 title: "CodingNinjas",
 items: ["Item1", "Item2"]
};

function showMenu({title = "Untitled", width = 200, height = 100, items = []}) {
 alert( `${title} ${width} ${height}` ); // CodingNinjas 200 100
 alert( items ); // Item1, Item2
}

showMenu(object1);

With the help of colon mappings and nested objects, we can use more complex destructuring.

let object1 = {
 title: "CodingNinjas",
 items: ["Item1", "Item2"]
};

function showMenu({
 title = "Untitled",
 width: w = 100,  // width goes to w
 height: h = 200, // height goes to h
 items: [item1, item2] }) {
 alert( `${title} ${w} ${h}` ); // CodingNinjas 100 200
 alert( item1 ); // Item1
 alert( item2 ); // Item2
}

showMenu(object1);

 

The full syntax for the function is same as the destructuring assignment:

function({
 incomingProperty: varName = defaultValue
 ...
})

We can observe that for an object of parameters, the variable varName will store the incomingProperty, if it is not defined then the defaultValue will be used.

Keep in mind that destructuring assumes that showMenu() has an argument. If we to get all the default values, then we can specify an empty object as an arguement as shown below:

showMenu({}); // ok, all values are default

showMenu(); // this would give an error

We can fix this by making {} the default value for the whole object of parameters.

Frequently Asked Questions (FAQs)

What is destructuring?
Destructuring assignment helps us to instantly map an object or array onto many variables.

What is the full object syntax?
let {propvarName = default, ...rest= object

This means that the property prop should be stored into the variable varName and, if no such property exists, then the default value as defined by us should be used.

Object properties that have no mapping are stored to the rest object.

What is the full array syntax?
let [item1 = defaultitem2...rest= array

The first item goes into item1; the second goes into item2, all the rest makes the array rest.

Key Takeaways

We learned about the concept of destructuring in javascript. This is an interesting technique of destructuring data structures in javascript that allows us to use individual elements of arrays and objects. This article also explained the implementation of array destructuring and object destructuring.

You can also expand your knowledge by referring to these articles on Javascript.

For more information about the react framework for frontend development, get into the entire Frontend web development course.

Happy Learning!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think