
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
[]
) are used:const fruits = ['apple', 'banana', 'grape']; const [firstFruit, secondFruit] = fruits; console.log(firstFruit); // 'apple' console.log(secondFruit); // 'banana'
Working with Objects
{}
) are used:const person = { name: 'Anvar', age: 22, }; const { name, age } = person; console.log(name); // 'Anvar' console.log(age); // 22
Renaming Variables
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
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
destructuring
and the spread
operator together when working with objects and arrays.Object and Spread:
const person = { name: 'Anvar', age: 22, city: 'Jizzakh', profession: 'Developer' }; // Destructuring to extract `name` and `age` const { name, age, ...rest } = person; console.log(name); // 'Anvar' console.log(age); // 22 console.log(rest); // { city: 'Jizzakh', profession: 'Developer' }
Array and Spread:
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']
spread
operator is also used for merging, updating, or copying objects or arrays, which greatly simplifies the coding process.Similar Articles
Main features of Reactjs
In this article, we will learn about the key features of React.js, which will also be useful for interview questions.
August 21, 2024First Class Function in JavaScript
Hello friends. In today's post, we'll go into detail about another important concept in JavaScript that plays a crucial role First Class Functions!
August 14, 2024What is React js? What role does React play in software development?
Today, we'll discuss React.js, one of the top JavaScript libraries, including its advantages, what we can do with it, and everything else you need to know in this post.
August 20, 2024What is an SPA (Single Page Application)?
Let's explore what an SPA (Single Page Application) is, which is used in today's modern websites.
August 29, 2024What is the DOM? What is the difference between HTML and the DOM?
In today’s post, we’ll discuss what the DOM (Document Object Model) is and the differences between HTML and the DOM.
August 31, 2024What is Virtual DOM?
What is Virtual DOM? How does it differ from Real DOM, and what are its main functions? Let's explore these in detail.
September 3, 2024