Default Values in Destructured Parameters
You'll learn how to provide fallback values when destructuring function parameters, ensuring your code handles missing properties without breaking.
The Problem Without Defaults
When you destructure parameters, what happens if a property doesn't exist? It becomes undefined, which can cause errors or unexpected behavior in your function body.
Combining Destructuring with Defaults
You can assign default values inside the destructuring pattern itself. If the property is missing (or undefined), the default kicks in:
function createUser({ name = 'Guest', age = 18 }) {
console.log(`${name} is ${age} years old`);
}
createUser({ name: 'Alice', age: 25 }); // "Alice is 25 years old"
createUser({ name: 'Bob' }); // "Bob is 18 years old"
createUser({}); // "Guest is 18 years old"
Why This Matters
Think of it like a restaurant order form with pre-checked boxes. If you don't specify a preference, the default is already filled in for you. This makes your functions more resilient to incomplete data.
Nested Destructuring with Defaults
You can even provide defaults within nested objects:
function displaySettings({ theme = 'light', font = { size: 14 } }) {
console.log(`Theme: ${theme}, Font size: ${font.size}`);
}
displaySettings({ theme: 'dark', font: { size: 16 } }); // "Theme: dark, Font size: 16"
displaySettings({ theme: 'dark' }); // "Theme: dark, Font size: 14"
displaySettings({}); // "Theme: light, Font size: 14"
Remember the Parameter Default
Don't forget: the entire parameter can also have a default (an empty object = {}), preventing errors if nothing is passed at all.
Key Takeaway: Combining destructuring with default values ({ prop = defaultValue }) lets you extract properties and provide fallbacks in one clean syntax, making functions graceful with incomplete data.