In today's article, we will explore in detail another important JavaScript syntax: Destructuring assignment.
Category
JavaScript
Javascript interview
Interview
Cover
Slug
javascript-destructuring-assignment
Date
‣
author
Published
Published
Assalomu Aleykum.
Today, we’re going to learn about a JavaScript syntax that we’ve encountered in many places, especially in OOP and various JavaScript frameworks and libraries, particularly in the import and export of modules.
Interestingly, many of us, including myself, have used this syntax without really knowing what it is 😀.
Let's not prolong the talk and get straight to the point!
In JavaScript, using the Destructuring assignment syntax, we can easily extract specific elements or values from arrays or objects into variables, which provides us with great convenience.
Working with Arrays
To extract values from an array, square brackets ([]) are used:
If you need to rename the object's property names, you can do it like this:
const person = {
name: 'Anvar',
age: 25
};
const { name: fullName, age: years } = person;
console.log(fullName); // 'Anvar'
console.log(years); // 25
// Here, the name and age properties are assigned to the fullName and years variables.
Default Values
If the extracted value doesn't exist, you can assign a default value:
const [first = 'Apple', second = 'Banana'] = [];
console.log(first); // 'Apple'
console.log(second); // 'Banana'
// If the array is empty, the first and second variables will have the values 'Apple' and 'Banana'.
Adding More
Combining Destructuring and Spread Operators
In the following example, we’ll look at how to use destructuring and the spread operator together when working with objects and arrays.
const fruits = ['apple', 'banana', 'grape', 'pomegranate'];
// Destructuring to extract the first element
const [firstFruit, ...remainingFruits] = fruits;
console.log(firstFruit); // 'apple'
console.log(remainingFruits); // ['banana', 'grape', 'pomegranate']
These methods are very useful in writing modular code in JavaScript, making the code more readable and concise. The spread operator is also used for merging, updating, or copying objects or arrays, which greatly simplifies the coding process.