Renaming Properties in Parameter Destructuring
What you'll learn: How to give destructured parameter properties clearer names when defining functions.
The Core Idea
Sometimes an object's property name doesn't make sense in your function's context. You can use aliasing syntax (the same : notation you learned in lesson 928) directly in function parameters to rename destructured properties into more meaningful variable names.
Why This Matters
Imagine you're working with a user object that has a property n for name. Inside your function, n isn't very descriptive. You want to use userName instead for clarity.
// Without renaming - unclear
function greet({ n }) {
console.log(`Hello, ${n}!`);
}
// With renaming - much clearer!
function greet({ n: userName }) {
console.log(`Hello, ${userName}!`);
}
const user = { n: 'Alice' };
greet(user); // "Hello, Alice!"
The Syntax
The pattern is { originalProperty: newName } in the parameter list:
function displayProduct({ p: productName, pr: price }) {
console.log(`${productName} costs $${price}`);
}
displayProduct({ p: 'Laptop', pr: 999 });
// "Laptop costs $999"
You're telling JavaScript: "Take the p property and call it productName inside this function."
Combining with Defaults
You can even combine renaming with default values:
function createProfile({ id: userId, role: userRole = 'guest' }) {
console.log(`User ${userId} is a ${userRole}`);
}
createProfile({ id: 42 });
// "User 42 is a guest"
Key Takeaway: Use { propertyName: newName } syntax in function parameters to destructure and rename properties simultaneously, making your function body more readable without changing the calling code.