Renaming Variables in JS Object Destructuring
Learn how to rename variables during JavaScript object destructuring. Covers basic renaming syntax, nested renaming, combining with defaults, real-world API transformation patterns, and common mistakes to avoid.
When you destructure an object, the extracted variables use the same names as the object properties by default. But sometimes the property names conflict with existing variables, use a different naming convention (like snake_case from an API), or are just not descriptive enough. JavaScript's destructuring syntax includes a colon-based renaming feature that solves all of these problems in a single expression.
This guide teaches you the renaming syntax, combines it with default values and nested patterns, and shows real-world use cases like API data transformation.
Basic Renaming Syntax
Use a colon after the property name to assign it to a new variable name:
const user = {
name: "Alice",
age: 28,
email: "alice@example.com"
};
// Rename during destructuring
const { name: userName, age: userAge, email: userEmail } = user;
console.log(userName); // "Alice"
console.log(userAge); // 28
console.log(userEmail); // "alice@example.com"
// The original property names are NOT available as variables
// console.log(name); // ReferenceError (no variable called 'name')The pattern is: { propertyName: newVariableName }. The left side (propertyName) tells JavaScript which property to extract. The right side (newVariableName) is the variable that receives the value.
Why Rename? Common Scenarios
Avoiding Variable Name Conflicts
const name = "Global User"; // Already exists
const user = {
name: "Alice",
role: "admin"
};
// Can't destructure as `name` — it already exists with const
// const { name } = user; // SyntaxError with const, or would shadow with let
// Rename to avoid conflict
const { name: firstName, role } = user;
console.log(firstName); // "Alice"
console.log(name); // "Global User" (original unchanged)Converting API Naming Conventions
Most APIs return data in snake_case, but JavaScript conventions use camelCase:
const apiResponse = {
user_id: 42,
first_name: "Alice",
last_name: "Johnson",
created_at: "2026-01-15T09:00:00Z",
is_active: true,
profile_image_url: "https://example.com/alice.jpg"
};
const {
user_id: userId,
first_name: firstName,
last_name: lastName,
created_at: createdAt,
is_active: isActive,
profile_image_url: profileImageUrl
} = apiResponse;
console.log(userId); // 42
console.log(firstName); // "Alice"
console.log(createdAt); // "2026-01-15T09:00:00Z"
console.log(profileImageUrl); // "https://example.com/alice.jpg"Making Generic Names More Descriptive
// API returns generic "data" and "count"
const response = {
data: [{ id: 1 }, { id: 2 }],
count: 2,
status: "success"
};
// Rename to be more specific
const { data: users, count: totalUsers, status: requestStatus } = response;
console.log(users); // [{ id: 1 }, { id: 2 }]
console.log(totalUsers); // 2
console.log(requestStatus); // "success"Renaming with Default Values
Combine renaming and defaults in a single expression using the pattern { prop: newName = default }:
const settings = {
bg_color: "#333",
font_size: 18
};
const {
bg_color: backgroundColor = "#fff",
font_size: fontSize = 16,
text_color: textColor = "#000", // Not in settings
border_radius: borderRadius = "4px" // Not in settings
} = settings;
console.log(backgroundColor); // "#333" (from object)
console.log(fontSize); // 18 (from object)
console.log(textColor); // "#000" (default applied)
console.log(borderRadius); // "4px" (default applied)Order of Operations
| What Happens | Example | Result |
|---|---|---|
| Property exists | { a: x = 5 } where a is 10 | x = 10 |
Property is undefined | { a: x = 5 } where a is undefined | x = 5 |
| Property missing | { a: x = 5 } where no a | x = 5 |
Property is null | { a: x = 5 } where a is null | x = null (default NOT applied) |
Property is 0 or "" | { a: x = 5 } where a is 0 | x = 0 (default NOT applied) |
Defaults only trigger for undefined, not for other falsy values.
Nested Object Renaming
Rename properties inside nested objects:
const order = {
order_id: "ORD-001",
customer: {
full_name: "Alice Johnson",
email_address: "alice@example.com"
},
shipping: {
street_address: "123 Main St",
city_name: "San Francisco",
zip_code: "94102"
}
};
const {
order_id: orderId,
customer: {
full_name: customerName,
email_address: customerEmail
},
shipping: {
city_name: city,
zip_code: zipCode
}
} = order;
console.log(orderId); // "ORD-001"
console.log(customerName); // "Alice Johnson"
console.log(customerEmail); // "alice@example.com"
console.log(city); // "San Francisco"
console.log(zipCode); // "94102"Renaming in Function Parameters
Rename properties directly in function parameter destructuring:
function createUserCard({
user_name: userName,
profile_pic: avatar = "/default-avatar.png",
is_verified: verified = false
}) {
return `
<div class="card ${verified ? "verified" : ""}">
<img src="${avatar}" alt="${userName}" />
<h3>${userName}</h3>
</div>
`;
}
const card = createUserCard({
user_name: "Alice",
profile_pic: "/alice.jpg",
is_verified: true
});
console.log(card);
// Outputs HTML card with Alice's infoAPI Data Processing Pipeline
function processApiUsers(apiUsers) {
return apiUsers.map(({
user_id: id,
first_name: firstName,
last_name: lastName,
email_address: email,
is_active: active = false,
created_at: createdAt
}) => ({
id,
firstName,
lastName,
email,
active,
createdAt: new Date(createdAt),
fullName: `${firstName} ${lastName}`
}));
}
const apiData = [
{
user_id: 1,
first_name: "Alice",
last_name: "Johnson",
email_address: "alice@example.com",
is_active: true,
created_at: "2026-01-15"
},
{
user_id: 2,
first_name: "Bob",
last_name: "Smith",
email_address: "bob@example.com",
created_at: "2026-02-20"
}
];
const users = processApiUsers(apiData);
console.log(users[0].fullName); // "Alice Johnson"
console.log(users[1].active); // false (default applied)Renaming with Rest Pattern
Combine renaming with the rest operator to extract and rename specific properties while collecting the remainder:
const config = {
bg_color: "#333",
text_color: "#fff",
font_size: 16,
line_height: 1.6,
max_width: "800px"
};
const {
bg_color: backgroundColor,
text_color: textColor,
...layoutSettings
} = config;
console.log(backgroundColor); // "#333"
console.log(textColor); // "#fff"
console.log(layoutSettings);
// { font_size: 16, line_height: 1.6, max_width: "800px" }Real-World Example: Database Record Transformer
function transformDatabaseRecords(records) {
return records.map(({
_id: id,
user_name: username,
email_addr: email,
pwd_hash: _password, // Extract but ignore (prefix with _)
created_ts: createdAt,
updated_ts: updatedAt,
is_admin: isAdmin = false,
...metadata
}) => ({
id,
username,
email,
isAdmin,
createdAt: new Date(createdAt),
updatedAt: new Date(updatedAt),
metadata
}));
}
const dbRecords = [
{
_id: "abc123",
user_name: "alice_j",
email_addr: "alice@example.com",
pwd_hash: "$2b$10$xyz...",
created_ts: 1706000000000,
updated_ts: 1706100000000,
is_admin: true,
login_count: 42,
last_ip: "192.168.1.1"
}
];
const cleanRecords = transformDatabaseRecords(dbRecords);
console.log(cleanRecords[0]);
// { id: "abc123", username: "alice_j", email: "...", isAdmin: true, createdAt: Date, updatedAt: Date, metadata: { login_count: 42, last_ip: "192.168.1.1" } }
// Notice: pwd_hash is completely excluded from the outputCommon Mistakes to Avoid
Confusing Rename Direction
const data = { name: "Alice" };
// WRONG mental model: "create 'name' from 'userName'"
// const { userName: name } = data; // This looks for 'userName' in data!
// CORRECT: "take 'name' from data, call it 'userName'"
const { name: userName } = data;
console.log(userName); // "Alice"The syntax reads: { source: destination }. Left side is the property name in the object. Right side is the new variable name.
Trying to Access Original Property Name After Renaming
const user = { name: "Alice" };
const { name: userName } = user;
console.log(userName); // "Alice" — this is the variable
// console.log(name); // ReferenceError — 'name' was not created as a variable!Missing Default for Nested Destructuring
const data = {};
// WRONG: crashes if nested object is missing
// const { user: { name: userName } } = data; // TypeError
// CORRECT: provide default empty object for the parent
const { user: { name: userName = "Guest" } = {} } = data;
console.log(userName); // "Guest"Rune AI
Key Insights
- Syntax:
{ property: newName }extracts the property and creates a variable with the new name - Direction: Left side is the source property, right side is the destination variable
- With defaults:
{ prop: newName = fallback }combines renaming and default values in one expression - API transformation: Rename at the boundary (fetch/response handler) to keep internal code in camelCase
- Original unavailable: After renaming, only the new variable name exists; the original property name is not a variable
Frequently Asked Questions
Can I rename and set a default at the same time?
Does renaming create a new copy of the value?
Is there a performance difference between renaming and direct destructuring?
Can I use computed property names with renaming?
How do I handle multiple APIs with different naming conventions?
Conclusion
Renaming during destructuring is a small syntax feature with significant practical impact. It eliminates naming conflicts, converts external naming conventions to your codebase style in one line, and makes extracted variables more descriptive. Combined with default values and nested patterns, renaming transforms messy API data into clean, well-named variables at the boundary of your code, keeping the rest of your application free from external naming quirks.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.