Destructuring: Arrays & Objects
Unpacking Data
Destructuring is an ES6 feature that allows you to easily extract values from Arrays and Objects and assign them to their own independent variables. It makes your code significantly cleaner.
Object Destructuring
Without destructuring, extracting data from an object is repetitive:
const user = { name: "Himanshu", role: "Full Stack" };
// The old way
let name = user.name;
let role = user.role;
The Modern Way (Destructuring):
const user = { name: "Himanshu", role: "Full Stack" };
const { name, role } = user;
console.log(name); // "Himanshu"
console.log(role); // "Full Stack"
We just created two variables (name and role) in a single line!
Array Destructuring
You can do the exact same thing with arrays, but it relies on position/index instead of key names.
const frameworks = ["React", "Next.js", "Vue"];
const [primary, secondary] = frameworks;
console.log(primary); // "React"
console.log(secondary); // "Next.js"
Skipping Values in Arrays
If you want the first and third value of an array, you simply leave an empty space in the destructuring array:
const [first, , third] = ["HTML", "CSS", "JS"];
console.log(third); // "JS"
💡 Himanshu's Tip:
You will use Object Destructuring constantly in React to extract "props". It is one of the most important syntactic sugar features introduced in modern JavaScript. Master it!
Interview Questions
- How does Object Destructuring differ from Array Destructuring in terms of extracting data?
- How can you rename a variable while destructuring an object?
- What happens if you try to destructure a property from an object that doesn't exist?