Destructuring Objects and Arrays
Topics
ReactJavascript
Published on
2 Jan 2025
Destructuring allows you to unpack values from arrays and properties from objects into distinct variables. This syntax simplifies the process of extracting data, making code more concise and readable.
Array Destructuring
Array destructuring enables you to assign elements of an array to variables in a single statement. The syntax is straightforward:
1const array = [1, 2, 3];
2const [first, second] = array;
3
4console.log(first); // 1
5console.log(second); // 2
Key Features:
- Skipping Elements: You can skip elements by leaving a blank space between commas:
1const array = [1, 2, 3, 4];
2const [first, , third] = array;
3
4console.log(third); // 3
- Default Values: You can assign default values if the array does not have enough elements:
1const array = [1];
2const [first, second = 2] = array;
3
4console.log(second); // 2
- Rest Operator: Use the rest operator (...) to gather remaining elements into a new array:
1const array = [1, 2, 3, 4];
2const [first, ...rest] = array;
3
4console.log(rest); // [2, 3, 4]
Object Destructuring
Object destructuring allows you to extract properties from an object and assign them to variables. The syntax is as follows:
1const obj = { a: 1, b: 2 };
2const { a, b } = obj;
3
4console.log(a); // 1
5console.log(b); // 2
Key Features:
- Renaming Variables: You can rename the variables while destructuring:
1const obj = { a: 1, b: 2 };
2const { a: firstValue, b: secondValue } = obj;
3
4console.log(firstValue); // 1
Default Values: Similar to arrays, you can set default values for properties:
1const obj = { a: 1 };
2const { a, b = 2 } = obj;
3
4console.log(b); // 2
Nested Destructuring: You can destructure nested objects directly:
1const obj = {
2 user: {
3 name: "John",
4 age: 30,
5 },
6};
7const { user: { name } } = obj;
8
9console.log(name); // John
Mixed Destructuring
You can combine both array and object destructuring in one statement. For example:
1const data = {
2 id: [1, 2],
3 name: "Alice"
4};
5
6const { id: [firstId], name } = data;
7
8console.log(firstId); // 1
9console.log(name); // Alice
Table of Contents