Destructuring Function Parameters with Objects
You'll learn how to unpack object properties directly in a function's parameter list, making your functions cleaner and more self-documenting.
The Core Idea
Instead of accepting a whole object as a parameter and then accessing its properties inside the function body, you can destructure the object right in the signature. This tells readers exactly which properties your function needs, and it eliminates repetitive dot-notation throughout the function.
Traditional approach:
function greetUser(user) {
console.log(`Hello, ${user.name}! You are ${user.age} years old.`);
}
greetUser({ name: 'Sarah', age: 28 });
With parameter destructuring:
function greetUser({ name, age }) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
greetUser({ name: 'Sarah', age: 28 });
// Hello, Sarah! You are 28 years old.
Notice how name and age are immediately available as standalone variables—no need for user.name or user.age.
Why This Matters
This pattern is especially valuable when functions receive configuration objects with many properties. You declare upfront which properties matter, and you can even add defaults:
function createProfile({ username, theme = 'dark', notifications = true }) {
console.log(`${username} prefers ${theme} theme, notifications: ${notifications}`);
}
createProfile({ username: 'alex' });
// alex prefers dark theme, notifications: true
The function signature becomes self-documenting—anyone reading it knows exactly what data is expected.
Key Takeaway:
Destructuring function parameters with objects extracts only the properties you need directly in the signature, eliminating dot-notation clutter and making your function's requirements crystal clear.