JavaScript: Destructuring in Function Parameters
Stop accessing object properties inside function bodies. Destructure them at the signature — your code gets cleaner, your intent gets clearer.
Technologies Discussed
The Pattern
Instead of passing an object and digging into it:
javascript
// Before — you have to read the body to know what's used
function createUser(user) {
console.log(user.name)
console.log(user.email)
console.log(user.role)
}
Destructure at the parameter level:
javascript
// After — the signature documents itself
function createUser({ name, email, role }) {
console.log(name)
console.log(email)
console.log(role)
}
The function body is cleaner. The signature tells you exactly what the function needs.
Default Values in Destructuring
javascript
function createUser({ name, email, role = 'viewer', active = true }) {
// role and active have fallbacks if not provided
}createUser({ name: 'Rajeev', email: 'r@example.com' }) // role = 'viewer', active = true
Renaming While Destructuring
When the incoming property name would conflict or isn't descriptive enough:
javascript
function renderProfile({ name: displayName, image: avatarUrl }) {
// use displayName and avatarUrl internally
return `<img src="${avatarUrl}" alt="${displayName}" />`
}
Nested Destructuring
javascript
function processOrder({ id, customer: { name, address: { city } } }) {
console.log(`Order ${id} for ${name} in ${city}`)
}
Use nested destructuring sparingly — it gets hard to read past two levels. For deeply nested objects, destructure in the body instead.
Works in Arrow Functions Too
javascript
const formatUser = ({ name, email }) => `${name} <${email}>`// Great for array methods const users = [{ name: 'Alice', email: 'a@co.com' }, { name: 'Bob', email: 'b@co.com' }] users.map(({ name, email }) => `${name} <${email}>`)
In React Components
This is especially valuable in React, where every component receives a props object:
tsx
// Common but verbose
const UserCard = (props) => {
return <div>{props.name} — {props.role}</div>
}// Clean and self-documenting const UserCard = ({ name, role, avatarUrl, isActive = true }) => { return ( <div className={isActive ? 'active' : 'inactive'}> <img src={avatarUrl} alt={name} /> <span>{name} — {role}</span> </div> ) }
Takeaway
Destructuring at the parameter level is a low-effort, high-readability win. It makes your functions self-documenting — you know exactly what they consume without reading the body. Adopt it as a default, not an exception.