Destructuring in JavaScript is a convenient way to extract values from arrays or objects and assign them to variables in a single statement.
It helps make code cleaner and more readable.
1️⃣ Array Destructuring
Used to unpack values from an array into separate variables.
const numbers = [10, 20, 30];
const [a, b, c] = numbers;
console.log(a); // 10
console.log(b); // 20
console.log(c); // 30
You can also skip elements or use default values:
const [x, , z = 50] = [5, 15];
console.log(x, z); // 5 50
2️⃣ Object Destructuring
Used to extract properties from an object into variables.
const user = { name: "Teekam", age: 25, city: "Jaipur" };
const { name, age } = user;
console.log(name); // Teekam
console.log(age); // 25
You can also rename variables:
const { name: fullName, city } = user;
console.log(fullName); // Teekam
console.log(city); // Jaipur
3️⃣ Nested Destructuring
You can destructure objects or arrays inside other objects or arrays.
const person = {
info: { firstName: "Teekam", lastName: "Singh" },
hobbies: ["Coding", "Cricket"]
};
const { info: { firstName }, hobbies: [hobby1] } = person;
console.log(firstName); // Teekam
console.log(hobby1); // Coding
4️⃣ Function Parameter Destructuring
You can destructure directly inside function parameters for cleaner code.
function displayUser({ name, age }) {
console.log(`${name} is ${age} years old`);
}
displayUser({ name: "Teekam", age: 25 });
💡 In Short:
Destructuring lets you unpack arrays or objects easily into individual variables —
making your code shorter, cleaner, and easier to read.