Destructuring in JavaScript
CSE Under grad. || Trying to be a better developer each day || Consistency is the key
One of the features that made my JavaScript code much cleaner and more readable is Destructuring. It felt like a small trick at first, but it quickly became one of my favorite parts of modern JavaScript.
What is Destructuring?
Destructuring allows you to unpack values from arrays or objects into individual variables in a very clean way.Instead of accessing properties or elements repeatedly, you can extract them in one line.
Array Destructuring
Old way
const numbers = [10, 20, 30]; const first = numbers[0]; const second = numbers[1];
//New way - Destructuring
const [first, second, third] = [10, 20, 30];
console.log(first); // 10 console.log(second); // 20
You can also skip values:
const [first, , third] = [10, 20, 30]; // skips 20
Object Destructuring
This is where destructuring becomes really powerful.js
const user = { name: "Sam", age: 28, city: "Bangalore", profession: "Developer" };
Old repetitive way
const name = user.name; const age = user.age; const city = user.city;
New clean way
const { name, age, city } = user;
console.log(name); // Sam
Default Values
You can assign default values if the property doesn’t exist:js
const { name, age, country = "India" } = user;
console.log(country); // India (if not present in object)
Before vs After Comparison
Before Destructuring:
function printUser(user) { const name = user.name; const age = user.age; const city = user.city;
console.log(\({name} is \){age} years old and lives in ${city}); }
After Destructuring:
function printUser({ name, age, city }) { console.log(\({name} is \){age} years old and lives in ${city}); }
Much cleaner and less repetitive!
Benefits of Destructuring
Reduces repetitive code (user.name, user.age, etc.)
Makes code more readable Great for function parameters
Helps when working with React props S
upports default values easily
Real Quick Example (React Props)
function Profile({ name, avatar, bio = "No bio available" }) { return
...
; }
conclusion
Destructuring is one of those modern JavaScript features that seems small but improves your daily coding experience significantly. Once you start using it, you’ll wonder how you lived without it.