Destructuring in JavaScript
Destructuring is a feature in JavaScript that allows you to extract data from arrays or objects into distinct variables.
It makes your code readable, concise, and expressive.
Destructuring is commonly used with frameworks like React, Angular, Vue, etc.
Using destructuring in your code makes it professional.
Syntax:
// Array Destructuring
[a, b] = [10, 20]; // a = 10, b = 20
[a, b] = array; // a = array[0], b = array[1]
[a, b, ...rest] = array; // a = array[0], b = array[1], rest = array[2:]
[a, b, c] = [10, 20]; // a = 10, b = 20, c = undefined
[a, b, c] = [10, 20, 30]; // a = 10, b = 20, c = 30
[a, , b] = [10, 20, 30]; // a = 10, b = 30
// Object Destructuring
{a, b} = {a: 10, b: 20}; // a = 10, b = 20
{a, b} = object; // a = object.a, b = object.b
{a, b, ...rest} = object; // a = object.a, b = object.b, rest = all other properties
{a, b, c} = {a: 10, b: 20}; // a = 10, b = 20, c = undefined
{a, b, c} = {a: 10, b: 20, c: 30}; // a = 10, b = 20, c = 30
{a, , b} = {a: 10, b: 20, c: 30}; // a = 10, b = 30
The above syntax may look confusing at first, but it's actually very simple.
Let's understand it with examples.
1. Array Destructuring
Let's say we have an array arr = [10, 20, 30, 40, 50]
.
Now, we want to extract the first two elements of the array into two variables a and b.
With destructuring, we can do it like this:
Example
let arr = [10, 20, 30, 40, 50];
// Array Destructuring
let [a, b] = arr;
console.log(a, b); // 10 20
Here, a is assigned the first element of the array, and b is assigned the second element of the array.
What about other elements of the array?๐ค We can use the rest operator to extract the remaining elements of the array.
Example
let arr = [10, 20, 30, 40, 50];
// Array Destructuring
let [a, b, ...rest] = arr;
console.log(a, b, rest); // 10 20 [30, 40, 50]
Here, rest variable is assigned the remaining elements of the array.
2. Object Destructuring
Just as we can extract elements from an array, we can also extract properties from an object directly into variables.
Let's say we have an object user = {name: 'Alex', isDeveloper: true, age: 25}
.
Now when we want to extract the name and age properties of the object into variables you would traditionally do it like this:
let user = {
name: 'Alex',
isDeveloper: true,
age: 25
};
// traditional way
let name = user.name;
let age = user.age;
But with destructuring, we can do it like this:
Example
let user = {
name: 'Alex',
isDeveloper: true,
age: 25
};
// Object Destructuring
let {name, age} = user;
console.log(name, age); // Alex 25
Note: The variable names should match the property names otherwise it will return undefined.
But you can also rename the variables while destructuring. Which we will see later in this section โญ๏ธ.
With object destructuring, we can also extract the remaining properties of the object into a variable using the rest operator.
Example
let user = {
name: 'Alex',
isDeveloper: true,
age: 25,
languages: ['JavaScript', 'Python', 'C++']
};
// Object Destructuring
let {name, age, ...rest} = user;
console.log(name);
console.log(age);
console.log(rest);
Here, the rest variable is assigned the remaining properties of the object.
3. Default Values
While destructuring arrays and objects above did you thought what if the property or element is not present in the object or array?๐ค
It will return undefined.
To solve this problem, we can use the default value syntax.
The default value can be provided while destructuring the array or object and when the property or element is not present in the object or array, it will return the default value.
Example
let user = {
name: 'Alex',
isDeveloper: true,
age: 25
};
// without default value ๐
var {name, age, country} = user;
console.log(name, age, country); // Alex 25 undefined
// with default value ๐
var {name, age, country = 'US'} = user;
console.log(name, age, country); // Alex 25 undefined
Here, the country variable is assigned the default value 'US' because the country property is not present in the object.
4. Renaming Variables
As we discussed above, we need to use the same variable name as the property name while destructuring an object.
But what if we want to use a different variable name?๐ค
For this, we can use the renaming syntax.
Renaming syntax: propertyName: newVariableName
Example
let user = {
name: 'Alex',
isDeveloper: true,
age: 25
};
// without renaming ๐
let {name, age} = user;
console.log(name, age); // Alex 25
// with renaming ๐
let {name: userName, age: userAge} = user;
console.log(userName, userAge); // Alex 25
Here, name is renamed to userName, and age is renamed to userAge.
5. Nested Destructuring
Nested destructuring is used to extract the properties of an object which is nested inside another object.
Here's an example:
Example
let user = {
name: 'Alex',
isDeveloper: true,
age: 25,
languages: ['JavaScript', 'Python', 'C++'],
address: {
city: 'New York',
state: 'NY'
}
};
// Nested Destructuring
let {name, age, languages, address: {city, state}} = user;
console.log(name);
console.log(age);
console.log(languages);
console.log(city);
console.log(state);
Here, address is destructured into city and state.
6. Destructuring Function Parameters
Some functions take an object as a parameter and we can use destructuring to extract the properties of the object inside the function.
Here's an example:
Example
function getUserInfo({name, age, languages}) {
console.log(name);
console.log(age);
console.log(languages);
}
let user = {
name: 'Alex',
isDeveloper: true,
age: 25,
languages: ['JavaScript', 'Python', 'C++']
};
getUserInfo(user);
Here, getUserInfo function takes an object as a parameter and destructures it into name, age and languages.
Multiple Example of Destructuring
Let's see some more examples of destructuring that may give you an idea of different use cases of destructuring.
Extracting specific elements of an array:
You can skip an element of an array by using a comma. For example, to skip the second element of an array, you can use const [a, , c] = array;
Example
const arr = [1, 2, 3, 4, 5];
const [a, , c] = arr;
console.log(a); // 1
console.log(c); // 3
Swapping values of two variables:
You can swap the values of two variables using destructuring.
Example
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
Extracting rest of the elements from an array or object:
When you extract a few elements from an array or object, you can use the rest operator to extract the rest of the elements.
Example
const arr = [1, 2, 3, 4, 5];
const [a, b, ...rest] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]
const obj = {a: 1, b: 2, c: 3, d: 4};
const {a, b, ...rest} = obj;
console.log(a); // 1
console.log(b); // 2
console.log(rest); // {c: 3, d: 4}
Destructuring nested arrays and objects:
Any nested array or object can be destructured. You just need to create same number of nested destructuring statements as the depth of the array or object.
Example
const arr = [1, [2, 3], 4];
const [a, [b, c], d] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4
const obj = {a: 1, b: {c: 2, d: 3}, e: 4};
const {a, b: {c, d}, e} = obj;
console.log(a); // 1
console.log(c); // 2
console.log(d); // 3
console.log(e); // 4
Using destructuring in for-of loops:
You can use destructuring in for-of loops to extract the elements of an array.
Example
const arr = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}];
for (const {a, b} of arr) {
console.log(a + b);
}
Using destructuring in async/await:
The response of an async function can be destructured to extract the data and error.
Example
async function fetchData() {
const response = await fetch('https://example.com');
const {data} = await response.json();
console.log(data);
}
fetchData();
Conclusion
So, this was all about destructuring in JavaScript. You have surely learned a lot about destructuring in this article.
Now it's all up to you to use destructuring in your code and make it more structured and readable.
Happy Coding!๐