Renaming Variables During Destructuring
You'll learn how to extract object properties into variables with different names than the original property keys.
The Problem
Sometimes the property names in an object don't match what you want to call your variables. Maybe the property name is too generic, conflicts with an existing variable, or doesn't follow your naming conventions. Basic destructuring uses the property name as the variable name:
const user = { name: "Alice", age: 30 };
const { name, age } = user;
console.log(name); // "Alice"
But what if you already have a name variable or want something more specific?
The Colon Syntax Solution
Use a colon (:) to rename properties during destructuring. The syntax is { originalPropertyName: newVariableName }:
const user = { name: "Alice", age: 30 };
const { name: userName, age: userAge } = user;
console.log(userName); // "Alice"
console.log(userAge); // 30
// console.log(name); // ReferenceError: name is not defined
Think of it like saying: "Take the property called name and put it into a variable I want to call userName."
Combining with Other Features
You can combine renaming with default values:
const settings = { theme: "dark" };
const { theme: userTheme, language: userLanguage = "en" } = settings;
console.log(userTheme); // "dark"
console.log(userLanguage); // "en" (default value used)
Key Takeaway: Use the colon syntax { propertyName: newVariableName } to assign object properties to variables with different names during destructuring, making your code clearer and avoiding naming conflicts.