Destructuring assignment is a great way to extract values from JavaScript arrays or properties from objects into distinct variables. This can lead to cleaner and more readable code, especially when working with complex data structures.
Let’s see some examples of array and object destructuring assignments in JavaScript.
Array Destructuring
// Array destructuring const numbers = [1, 2, 3]; const [first, second, third] = numbers; console.log(first); // Output: 1 console.log(second); // Output: 2 console.log(third); // Output: 3
In this example, numbers
is an array, and by using array destructuring, we assign each element of the array to a corresponding variable (first
, second
, and third
). This is more concise than accessing array elements using indices (numbers[0]
, numbers[1]
, etc.).
Object Destructuring
// Object destructuring const person = { name: 'Aman', age: 30 }; const { name, age } = person; console.log(name); // Output: Aman console.log(age); // Output: 30
Here, person
is an object, and object destructuring is used to extract the values of name
and age
properties into variables with the same names. This syntax is more straightforward than accessing object properties directly (person.name
, person.age
).
Set Default Value in Destructuring
You can also assign default values during destructuring arrays or objects, making it more flexible. See the following code example.
const person = { name: 'Aman' }; const { name, age = 30 } = person; console.log(name); // Output: Aman console.log(age); // Output: 30 (default value assigned)
Destructuring assignment is a powerful feature that simplifies the process of working with arrays and objects in JavaScript. It’s widely used to extract values more elegantly and expressively.