Master Destructuring in One Go
Source: Dev.to
What Destructuring Means
Destructuring is a JavaScript expression that lets you extract values from arrays, objects, maps, and sets in a concise way. Instead of accessing each property or element individually, you can pull multiple values in a single statement.
Destructuring Objects
const person = {
name: "kunal",
bio: "like this blog",
twitter: "@kunalmadoliya"
};
// Traditional way
const name = person.name;
const twitter = person.twitter;
console.log(name, twitter); // kunal @kunalmadoliya
// Destructuring
const { name, twitter } = person;
console.log(name, twitter); // kunal @kunalmadoliya
The line { name, twitter } = person tells JavaScript to create variables name and twitter and assign them the corresponding values from person.
Nested Object Destructuring
const user = {
id: 1,
name: "Kunal",
contact: {
email: "kunal@example.com",
phone: {
countryCode: "+91",
number: "9876543210"
}
},
skills: ["JavaScript", "React", "Node.js"]
};
// Extracting nested values
const {
contact: {
phone: { countryCode, number: phoneNumber }
}
} = user;
console.log(countryCode, phoneNumber); // +91 9876543210
This extracts deep properties in a single, readable statement.
Destructuring Arrays
const arr = ["kunal", "@kunalmadoliya", "like this blog"];
// Traditional way
const first = arr[0];
const second = arr[1];
const third = arr[2];
console.log(first, second, third); // kunal @kunalmadoliya like this blog
// Destructuring
const [first, second, third] = arr;
console.log(first, second, third); // kunal @kunalmadoliya like this blog
Array destructuring assigns each element to a variable based on its position.
Default Values
You can provide fallback values for properties that might be missing:
const { name, age, bio = "Unknown" } = person;
console.log(bio); // Output: Unknown (if `bio` is not defined)
If bio is absent in the source object, it defaults to "Unknown".
Benefits of Destructuring
- Cleaner syntax – avoids long chains of property accesses.
- Improved readability – code is easier to understand at a glance.
- Less repetition – no need to repeat the object name for each property.
- Multiple values in one line – extract several variables simultaneously.
- Support for nested data – directly access deep properties without intermediate variables.
Happy coding!