
JavaScript gives us a feature called destructuring. It makes working with arrays and objects much cleaner and less repetitive.
If you have ever written code like this:
const user = { name: "Ashish" age: 22 };
const name = user.name;
const age = user.age;
You already know the pain of writing the same object while extracting each value from the object
Let鈥檚 fix that.
What is destructuring?
Destructuring is a syntax which is introduced in ES6 (ECMAScript 2015), that allows to extract values from arrays or objects into variables in a simple, shorter, and cleaner way.
Update the same example using destructuring:
const user = { name: "Ashish" age: 22 };
const {name, age} = user;
Now JavaScript does the work for you. You do not have to write user.name over.
Destructuring Objects
Object destructuring is based on keys (property names).
Before ES6,
const user = {
name: "Ashish",
age: 22
};
const name = user.name;
const age = user.age;
After (Destructuring):
const { name, age } = user;
Renaming Variables: We can also rename the variables on the go, while destructuring.
const { name: username } = user;
Default Values: We can also assign the default values while destructuring objects
const user = {
name: "Ashish"
};
const { name, age = 18 } = user;
console.log(age); // 18
Destructuring Arrays
Array destructuring works based on position (also called index).
Before ES6,
const colors = ['red', 'blue', 'pink'];
const first = colors[0];
const second = colors[1];
const third = colors[2];
After ES6, destructuring is much easier.
const colors = ['red', 'blue', 'pink'];
const [first, second, third] = colors;
Just in case, we do not want a second color:
const colors = ['red', 'blue', 'pink'];
const [first, , third] = colors;
This is fine for one or a maximum of 2 indexes, but we should not skip multiple indexes by keeping empty for so many positions in between. In that case, we can use the older approach const color = colors[10];
Why Use Destructuring?
Less Repetitive Code
Cleaner and more readable
Final Thoughts
Destructuring is one of those features that:
Reduces boilerplate
Improves readability
Makes your code feel more modern
Start using it in small places, and soon it鈥檒l become second nature.
Follow series to learn more about Javascript.
Comments
Join the discussionNo comments yet. Be the first to comment.
JavaScript: Beginner to Advance 馃殌
This blog series is designed for professionals who want to learn JavaScript step by step. Starting from the basics like variables and data types, we gradually move to functions, DOM manipulation, and real-world mini projects.

