Default Values in Object Destructuring
You'll learn how to protect your code from undefined by setting fallback values when destructuring objects.
Why Default Values Matter
When you destructure an object, there's no guarantee the property you're looking for actually exists. Maybe it's missing from the API response, or perhaps it was never set. Without a default value, you'd get undefined—which can break your logic.
The Basic Pattern
Use the = operator right after the property name to specify a fallback:
const user = { name: "Alice" };
// Without default: age is undefined
const { name, age } = user;
console.log(age); // undefined
// With default: age falls back to 25
const { name: userName, age: userAge = 25 } = user;
console.log(userAge); // 25
How It Works
Think of default values as a safety net. JavaScript first checks: "Does this property exist?" If yes, use its value. If no (or if it's explicitly undefined), use the default instead.
const settings = { theme: "dark" };
const { theme = "light", fontSize = 16 } = settings;
console.log(theme); // "dark" (property exists)
console.log(fontSize); // 16 (property missing, default used)
Combining with Renaming
You can rename variables and provide defaults simultaneously:
const response = { status: "ok" };
const { status: requestStatus = "pending", data: responseData = [] } = response;
console.log(requestStatus); // "ok"
console.log(responseData); // [] (default used)
The pattern is: { originalName: newName = defaultValue }
Key Takeaway: Default values in object destructuring prevent undefined errors by providing fallback values for missing or undefined properties—making your code more resilient and predictable.