ES6 (ECMAScript 2015) introduced many powerful features in JavaScript, and one of the most useful is destructuring. It allows you to unpack values from arrays or properties from objects into distinct variables in a very clean and readable way.
Let’s understand it with simple examples.
Destructuring Arrays
Instead of accessing array elements one by one, destructuring lets you extract them in a single line.
Old Way:
const colors = ['red', 'green', 'blue'];
const first = colors[0];
const second = colors[1];
With Destructuring:
const [first, second, third] = ['red', 'green', 'blue'];
console.log(first); // red
console.log(second); // green
You can also skip items:
const [,, third] = ['red', 'green', 'blue'];
console.log(third); // blue
Destructuring Objects
With objects, destructuring lets you extract multiple properties at once.
Old Way:
const person = { name: 'Kirti', age: 25 };
const name = person.name;
const age = person.age;
With Destructuring:
const { name, age } = person;
console.log(name); // Kirti
console.log(age); // 25
You can also rename variables:
const { name: userName } = person;
console.log(userName); // Kirti
Default Values in Destructuring
You can assign default values if the value is undefined
.
Array Example:
const [a = 10, b = 20] = [5];
console.log(a); // 5
console.log(b); // 20
Object Example:
const { city = 'Delhi' } = { name: 'Kirti' };
console.log(city); // Delhi
Nested Destructuring
You can extract values from nested objects or arrays too.
Nested Object Example:
const user = {
name: 'Kirti',
address: {
city: 'Mumbai',
pin: 400001
}
};
const {
address: { city, pin }
} = user;
console.log(city); // Mumbai
Nested Array Example:
const numbers = [1, [2, 3]];
const [one, [two, three]] = numbers;
console.log(two); // 2
Destructuring in Function Parameters
You can destructure directly inside function parameters.
Object Example:
function greet({ name, age }) {
console.log(`Hello ${name}, age ${age}`);
}
greet({ name: 'Kirti', age: 25 });
Array Example:
function sum([a, b]) {
return a + b;
}
console.log(sum([3, 4])); // 7
Why Use Destructuring?
- Cleaner and shorter code
- Makes code more readable
- Easier to work with objects and arrays
- Useful in React, APIs, and large projects
Quick Summary
Type | Syntax Example |
---|---|
Array | const [a, b] = [1, 2]; |
Object | const {x, y} = {x: 10, y: 20}; |
Nested | const {a: {b}} = obj; |
Rename | const {x: newX} = obj; |
Default Value | const [a = 1] = []; |
Functions | function({name}) {} or function([a]) {} |
Final Thought
ES6 Destructuring is a simple but powerful tool that helps make your JavaScript cleaner, more expressive, and easier to maintain. Whether you’re building a small script or a big web app, it’s a must-know feature for modern developers.