Destructuring assignment provides a concise way to extract and work with values from arrays and objects in JavaScript.

- Makes code shorter and easier to read.
- Allows multiple values to be assigned at once.
- Supports arrays, objects, and nested data structures.
- Simplifies variable swapping and function return handling.
Array Destructuring
Array destructuring allows elements of an array to be assigned to individual variables based on their positions.
const a = [10, 20, 30, 40];
console.log("Example 1");
const [x, y, z, w] = a;
console.log(x);
console.log(y);
console.log(z);
console.log(w);
console.log("Example 2");
const [p, q, , r] = a;
console.log(p);
console.log(q);
console.log(r);
console.log("Example 3");
const [s, t] = a;
console.log(s);
console.log(t);
Output
Example 1 10 20 30 40 Example 2 10 20 40 Example 3 10 20
Array Destructuring with Rest Element
The rest element (...) collects the remaining array elements into a new array. It must be the last element in a destructuring pattern.
const [first, , ...rest] = ["a", "b", "c", "d"];
console.log(first);
console.log(rest);
Output
a [ 'c', 'd' ]
Swapping Variables Using Destructuring
Destructuring can be used to swap the values of two variables without using a temporary variable.
let x = 10;
let y = 20;
[x, y] = [y, x];
console.log(x);
console.log(y);
Output
20 10
Destructuring Function Return Values
Destructuring can extract values directly from an array returned by a function.
function namesList() {
return ["a", "b", "c", "d"];
}
const [first, second] = namesList();
console.log(first);
console.log(second);
Output
a b
Object Destructuring
Object destructuring allows properties of an object to be assigned to variables using their property names.
const marks = {
x: 21,
y: -34,
z: 47
};
const { x, y, z } = marks;
console.log(x);
console.log(y);
console.log(z);
Output
21 -34 47
Object Destructuring with Rest
The rest property collects the remaining properties of an object into a new object.
const { x, y, ...rest } = {
x: 10,
y: 20,
m: 30,
n: 40
};
console.log(x);
console.log(y);
console.log(rest);
Output
10
20
{ m: 30, n: 40 }
Nested Object Destructuring
Nested objects can also be destructured by following their property hierarchy.
const marks = {
section1: {
alpha: 15,
beta: 16
},
section2: {
alpha: -31,
beta: 19
}
};
const {
section1: {
alpha: alpha1,
beta: beta1
}
} = marks;
console.log(alpha1, beta1);
Output
15 16
Accessing Deeply Nested Properties
Destructuring can extract properties from multiple levels of a nested object.
const obj = {
name: "GFG",
add: {
country: "India",
state: {
code: "JS",
pincode: "820800",
article: {
topic: "destructuring"
}
}
}
};
const { name } = obj;
console.log(name);
const {
add: {
country
}
} = obj;
console.log(country);
const {
add: {
state: {
code
}
}
} = obj;
console.log(code);
const {
add: {
state: {
article: {
topic
}
}
}
} = obj;
console.log(topic);
Output
GFG India JS destructuring