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);

You can also try this code with Online Javascript Compiler
Run Code
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);

You can also try this code with Online Javascript Compiler
Run Code
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

You can also try this code with Online Javascript Compiler
Run Code
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

You can also try this code with Online Javascript Compiler
Run Code
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
}

You can also try this code with Online Javascript Compiler
Run Code
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
}

You can also try this code with Online Javascript Compiler
Run Code
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!

You can also try this code with Online Javascript Compiler
Run Code
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

You can also try this code with Online Javascript Compiler
Run Code
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

You can also try this code with Online Javascript Compiler
Run Code
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

You can also try this code with Online Javascript Compiler
Run Code
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)

You can also try this code with Online Javascript Compiler
Run Code
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

You can also try this code with Online Javascript Compiler
Run Code
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 = []) {
// ...
}

You can also try this code with Online Javascript Compiler
Run Code
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"])

You can also try this code with Online Javascript Compiler
Run Code
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);

You can also try this code with Online Javascript Compiler
Run Code
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);

You can also try this code with Online Javascript Compiler
Run Code
The full syntax for the function is same as the destructuring assignment:
function({
incomingProperty: varName = defaultValue
...
})

You can also try this code with Online Javascript Compiler
Run Code
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

You can also try this code with Online Javascript Compiler
Run Code
We can fix this by making {} the default value for the whole object of parameters. Also, for good practice implement it on an online javascript compiler.
Read Also - Difference between argument and parameter
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 {prop : varName = 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 = default, item2, ...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!