Destructuring In JavaScript
The beginner's guide to mastering destructuring
Destructuring is a powerful tool that allows us to extract values from arrays or objects and bind them to variables concisely and elegantly.
It wasn't always like that. Rather, before the introduction of ES6, extracting values from complex data structures often required multiple lines of code and manual assignments. Destructuring simplifies this process by providing a more intuitive and efficient way to unpack values.
Since its introduction, destructuring has become widely adopted by JavaScript developers due to its readability and convenience. It has become an essential tool for tasks such as function parameter handling, array manipulation, object property extraction, and more.
It is also one of the core concepts that must be understood in JavaScript before learning frameworks such as React, Vue, etc.
By the end of this article, you'd have been equipped with the knowledge and tools to leverage the full potential of destructuring, unlocking a new level of productivity and elegance in your code. So, without further ado, let's embark on this journey to unravel the art of destructuring in JavaScript!
What Is Destructuring?
Destructuring is a feature in JavaScript that allows you to extract values from arrays or properties from objects and assign them to variables using a concise and declarative syntax.
Consider the array literal expression below:
const even=[2,4,6,8,10]
const first=even[0]
const second=even[1]
const third=even[2]
console.log(first) //2
console.log(second) //4
console.log(third) //6
To obtain the first item in the array, you typically create a variable and assign it to the element in the zeroth index. To get the second element, you go through the same process.
What if instead of that, you could just create all the variables at a go, and unpack the values from the variable? That's exactly what destructuring allows us to do. For example :
const even=[2,4,6,8,10]
const [first, second,third]=even
console.log(first) //2
console.log(second) //4
console.log(third) //6
Note that here we did the same thing as in the previous example. However, this syntax is more concise and also more elegant.
Let's explain the syntax:
The square bracket on the left-hand side is the first indication that an array destructuring is about to happen.
const []=even // Square bracket on the left means array destructuring
const even=[] // Square bracket on the right is array literal expression
The first variable in the square bracket is assigned to the element with the index 0, the second with the index 1, and so on.
[two, four,six]=even
Object destructuring also follows the same pattern as array destructuring.
const person = {
name:'Abdqudus',
language:'JavaScript',
currentTopic:'Destructuring In JavaScript'
}
const {name, language, currentTopic}=person
console.log(name) //Abdqudus
console.log(language) //JavaScript
console.log(currentTopic) //Destructuring In JavaScript
Destructuring Patterns
There are two different ways to destructure an array or object in JavaScript:
Binding
Assignment
Binding: This pattern starts with a variable declaration with any keyword of your choice. Then each property is bound to a variable.
This is the approach used in all of the previous examples.
Assignment: Here, the destructuring assignment does not start with a keyword. Rather, each destructured property is assigned to the target of the assignment.
This target might have been declared earlier with either var
or let
.
For example:
const even=[2,4,6,8,10]
const person = {
name:'Abdqudus',
language:'JavaScript',
currentTopic:'Destructuring In JavaScript'
}
var first, second, third
let name, language,currentTopic
[first, second, third]=even
{name, language, currentTopic}=person
This target could also be a property of another object.
For example:
const detailsArr=[]
const user={
name:'John',
followers:200,
followings:1500
}
({name:detailsArr[0], followers:detailsArr[1], followings:detailsArr[2]}=user)
console.log(detailsArr) //['John',200,1500]
Here's a breakdown of the code above:
A constant
detailsArr
was declared and then set to an empty array.A user object was created.
The keys in the user object were assigned a new variable name. This was achieved with the
:
symbol.The object was then destructured.
Notes:
When using this approach(assignment) to destructure an object, the parenthesis is compulsory. Without it, the engine will not consider it an object literal, rather, it will assume that it is a block.
The parenthesis needs to be preceded by a semicolon, else, the engine will assume it's a function call for whatever line of code was before it.
Default Values
Destructuring allows setting a default value as a fallback. If the property to be destructured is undefined or is not present, the default value is used.
const odd=[1,3,5]
const [first, second, third, fourth=9]=odd
console.log(fourth) //9
const user={
name:'Ahmed',
followers:500,
followings:500
}
const {name, followers, followings, age=25}=user
console.log(age) //25
Rest Property
Destructuring allows packing multiple properties into an array or object. This is done with the rest syntax.
const scoreArray=[100, 49, 40,33, 25]
const grade = {Maths: "A",Physics: "B",Chemistry: "B",Biology: "E"}
const [maximum, ...fail]=scoreArray
const { Maths, ...others } = grade;
console.log(fail) //[49,40,33,25]
console.log(others) // {Physics: "B", Chemistry: "B", Biology: "E" }
Every item asides from the one specified are packed into another array or object with the name of the array or object being whatever comes after the rest syntax; fail and others in this example.
Destructuring with special syntaxes
There are certain syntaxes where JavaScript binds variables for you. Some of those syntaxes include:
for of loop;
function parameters
catch variables in a catch block
A for
of
loop without destructuring can be written as follows:
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 35 }
];
for (const user of users) {
console.log(Name: ${user.name}, Age: ${user.age});
} //Name: John, Age: 25 //Name: Jane, Age: 30 //Name: Bob, Age: 35
However, destructuring can make it more concise as shown below:
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 35 }
];
for (const { name, age } of users) {
console.log(Name: ${name}, Age: ${age});
}
//Name: John,
//Age: 25
//Name: Jane,
//Age: 30
//Name: Bob,
//Age: 35
Destructuring can also be beneficial when working with function parameters, allowing you to extract values from objects or arrays conveniently. Here's an example showcasing destructuring in function parameters using an object:
function greetUser({ name, age }) {
console.log(Hello, ${name}! You are ${age} years old.);
}
const user = { name: 'Alice', age: 28 };
greetUser(user);
//Hello, Alice!, you are 28 years old.
Destructuring can also be used in the catch block of a try-catch statement to extract information from caught error objects. Here's an example that demonstrates destructuring in a catch block:
try {
if (true) {
throw new Error("Something went wrong!");
}
} catch ({ message }) {
console.log(`Caught an error: ${message}`);
} //Caught an error: Something went wrong!
Some Use Cases For Array Destructuring
Variable Assignment:
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
Unpacking With More Elements Than Source: If the number of variables on the left is greater than the length of the array to be destructured, the variables will be assigned values from left to right. Whatever is left after this will be assigned a value of undefined
.
const numbers = [1, 2, 3];
const [a, b, c, d, e] = numbers;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); //undefined
console.log(e); //undefined
Swapping Values Of Variables: Swapping the values of variables is a common use case for array destructuring. Here's an example of how you can swap variables using array destructuring in JavaScript:
let a = 10;
let b = 20;
//Before swapping
console.log('a:', a); // Output: 10
console.log('b:', b); // Output: 20
[a, b] = [b, a];
//After swapping
console.log('a:', a); // Output: 20
console.log('b:', b); // Output: 10
Parsing Arrays Returned From A Function: Array destructuring is a convenient way to extract variables from an array returned from a function, and then assign individual values to these variables.
function getNumbers() {
return [1, 2, 3];
}
const [a, b, c] = getNumbers();
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
Some Use Cases For Object Destructuring
Assigning To New Variable Names: As shown in a previous example, object destructuring allows unpacking an object using its keys and simultaneously assigning a new variable to the values unpacked.
const person = {firstName: 'John', lastName: 'Doe', age: 30 };
const { firstName: fName, lastName: lName, age } = person;
console.log(fName); // Output: John
console.log(lName); // Output: Doe
console.log(age); // Output: 30
Conclusion
As you can see, destructuring is a powerful tool provided by JavaScript to write concise and elegant codes. Mastering it takes one's code to the next level
To learn more about destructuring, visit Mozilla Developer Network (MDN).