Default Values in Destructured Parameters
What you'll learn: How to combine destructuring with default values in function parameters to handle missing or undefined properties gracefully.
The Core Idea
When you destructure objects or arrays in function parameters, you can assign default values directly in the destructuring pattern. This means if a property is missing or undefined, the default kicks in automatically—no extra if checks needed.
Think of it like ordering a custom pizza: if someone forgets to specify the size, you assume "medium" by default. You don't need to stop and ask—you've already planned for it.
Object Parameter Destructuring with Defaults
function greetUser({ name = "Guest", age = 18 } = {}) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
greetUser({ name: "Alice", age: 25 }); // "Hello, Alice! You are 25 years old."
greetUser({ name: "Bob" }); // "Hello, Bob! You are 18 years old."
greetUser({}); // "Hello, Guest! You are 18 years old."
greetUser(); // "Hello, Guest! You are 18 years old."
Notice the = {} at the end? That's a default for the entire parameter object, preventing errors when the function is called with no arguments at all.
Array Parameter Destructuring with Defaults
function setDimensions([width = 100, height = 200] = []) {
console.log(`Width: ${width}, Height: ${height}`);
}
setDimensions([300, 400]); // "Width: 300, Height: 400"
setDimensions([500]); // "Width: 500, Height: 200"
setDimensions([]); // "Width: 100, Height: 200"
setDimensions(); // "Width: 100, Height: 200"
Each destructured element can have its own fallback, and the = [] prevents errors when nothing is passed.
Key Takeaway: Default values in destructured parameters make functions resilient to missing data, eliminating the need for manual checks and making your code cleaner and more predictable.