Object Destructuring
Overview
Object Destructuring (ES6) allows you to extract properties from an object and bind them to standalone variables in a single line of code.
Unlike Array destructuring (which relies on index position), Object destructuring relies on the exact property name. This makes it incredibly robust, as the order of properties doesn't matter.
Syntax
const user = { name: "Kartik", role: "Developer", age: 22 };
// The variable names MUST MATCH the object keys exactly!
// Order doesn't matter.
const { role, name } = user;
console.log(name); // "Kartik"
console.log(role); // "Developer"const settings = { theme: "dark" };
// Rename 'theme' to 'appTheme'
// Provide a default 'fontSize' just in case it's missing!
const { theme: appTheme, fontSize = 14 } = settings;
console.log(appTheme); // "dark"
console.log(fontSize); // 14Common Pitfalls
- Trying to destructure a deeply nested property without ensuring the parent object exists. If
user.addressis undefined, doingconst { city } = user.addresswill throw a fatalTypeError: Cannot destructure property 'city' of undefined.
Interview Questions
Array destructuring binds variables based on their position in the array, meaning you can name the variables whatever you want. Object destructuring binds based on the property name (key), meaning the variable names must match the keys exactly (unless you explicitly rename them using the : syntax).
Real-World Example
Destructuring the props object immediately inside the parameter list of a React functional component for incredibly clean code.
// Instead of (props) and typing props.title
function Card({ title, imageUrl }) {
return <h1>{title}</h1>;
}Check Your Knowledge
Test your understanding of Object Destructuring with these quick questions.