Renaming Variables During JS Destructuring Guide
A complete guide to renaming variables during JavaScript destructuring. Learn the colon syntax for object destructuring aliases, combining renaming with default values, renaming in nested patterns, function parameter renaming, and practical use cases for avoiding name collisions.
JavaScript destructuring does not require you to use the same variable name as the property name. The colon syntax (property: newName) lets you assign to a different local variable name — a technique called destructuring aliasing. This is useful for avoiding name collisions, shortening verbose API property names, or clarifying intent.
The Renaming Syntax
In object destructuring, the pattern { source: target } means: extract the property named source from the object and store it in a variable named target:
const user = { name: "Alice", age: 30 };
// Without renaming
const { name, age } = user;
// name="Alice", age=30
// With renaming
const { name: userName, age: userAge } = user;
// userName="Alice", userAge=30
// name and age are NOT created as variablesThe colon in destructuring means "rename to", not a value assignment.
When to Use Renaming
Avoiding Name Collisions
function processRequest(request, response) {
const { headers, body: requestBody } = request; // body renamed to requestBody
const { body: responseBody, status } = response; // body renamed to responseBody
// Now we have both requestBody and responseBody without conflict
console.log(requestBody, responseBody);
}Without renaming, two body properties would clash. Renaming gives each a unique name in the local scope.
Shortening Verbose External API Property Names
Third-party APIs often have long or generic property names:
const apiData = {
user_display_name: "Alice Smith",
user_account_id: "acc_12345",
subscription_tier_name: "Premium",
account_creation_timestamp: 1709500000000,
};
// Rename to concise local names
const {
user_display_name: displayName,
user_account_id: accountId,
subscription_tier_name: tier,
account_creation_timestamp: createdAt,
} = apiData;
// Now use clean names throughout the function
console.log(displayName); // "Alice Smith"
console.log(accountId); // "acc_12345"Clarifying Intent
const { value: inputValue } = document.getElementById("search");
// More descriptive than just 'value' — clarifies it comes from the input elementCombining Renaming With Default Values
To both rename and provide a default, the syntax is { property: newName = defaultValue }:
const config = { timeout: 5000 };
const {
timeout: requestTimeout = 3000, // rename + default
retries: maxRetries = 3, // rename + default (retries is absent)
debug: isDebug = false, // rename + default
} = config;
// requestTimeout=5000 (from config)
// maxRetries=3 (default, retries absent)
// isDebug=false (default, debug absent)The mental model: { source: target = default } — extract source, call it target, use default if source is undefined.
Renaming in Nested Destructuring
Renaming works at any depth in nested patterns:
const response = {
status: 200,
payload: {
user: {
id: 42,
profile: {
fullName: "Bob Jones",
email: "bob@example.com",
},
},
},
};
const {
status: httpStatus,
payload: {
user: {
id: userId,
profile: {
fullName: name,
email,
},
},
},
} = response;
// httpStatus=200, userId=42, name="Bob Jones", email="bob@example.com"Each level can independently rename. Intermediate path segments (like payload, user, profile) are not bound as variables.
Renaming in Function Parameters
Function parameters are perhaps the most common place for renaming with defaults:
// Rename API snake_case to camelCase in function params
function renderProfile({ first_name: firstName, last_name: lastName, avatar_url: avatar = "/default.png" }) {
return `<img src="${avatar}" alt="${firstName} ${lastName}">`;
}
renderProfile({
first_name: "Alice",
last_name: "Smith",
// avatar_url not provided — uses default
});
// <img src="/default.png" alt="Alice Smith">This pattern is powerful when consuming REST APIs that use snake_case while your JavaScript uses camelCase.
Array Destructuring — No Renaming Needed
Array destructuring always assigns to new names since there are no property keys to conflict with:
const [first, second] = [10, 20]; // You choose the names freely
// Renaming concept doesn't apply — the extract is positional
const [, middle] = [1, 2, 3]; // middle=2, freely namedIf you want to "rename" from a destructured array, you simply write whatever name you want.
Comparison: With and Without Renaming
| Pattern | How It Works |
|---|---|
const { a } = obj | Extracts obj.a into variable a |
const { a: b } = obj | Extracts obj.a into variable b |
const { a = 10 } = obj | Extracts obj.a into a; default 10 if obj.a is undefined |
const { a: b = 10 } = obj | Extracts obj.a into b; default 10 if obj.a is undefined |
const { a: { b } } = obj | Nested: extracts obj.a.b into b |
const { a: { b: c } } = obj | Nested + rename: extracts obj.a.b into c |
Practical Pattern: API Response Normalization
// Normalize a paginated API response to local naming conventions
function normalizePaginatedResponse({
data: items = [],
meta: {
current_page: page = 1,
per_page: pageSize = 20,
total: totalItems = 0,
last_page: totalPages = 1,
} = {},
}) {
return { items, page, pageSize, totalItems, totalPages };
}
const response = {
data: [{ id: 1 }, { id: 2 }],
meta: { current_page: 2, per_page: 10, total: 45, last_page: 5 },
};
console.log(normalizePaginatedResponse(response));
// { items: [{id:1},{id:2}], page: 2, pageSize: 10, totalItems: 45, totalPages: 5 }This is one of the most practical patterns in real-world API integration code — bridging the gap between a server's naming conventions and your application's conventions in a single declarative statement.
Rune AI
Key Insights
- { source: target } syntax extracts source and binds it to target: The colon means "rename to" — source is the property key on the object; target is the new local variable name
- source is NOT created as a variable: const { name: userName } = obj creates userName but not name — a common gotcha for developers new to the syntax
- Combine rename with default: { prop: newName = defaultValue } — if prop is undefined on the object, newName receives defaultValue
- Works at any nesting depth: Each level of nested destructuring can independently rename the extracted value
- Most practical for API integration: Bridging snake_case server responses to camelCase application code at the destructuring site keeps normalization declarative and localized
Frequently Asked Questions
Does renaming affect the original object?
Can I use the same name for renamed and non-renamed properties in the same destructure?
What if I want to rename and use rest?
Is there a way to do this with computed property names?
Conclusion
The renaming syntax in object destructuring ({ property: newName }) is a concise way to extract values under different local names. Combine it with defaults ({ prop: name = default }) and nesting for powerful, readable data extraction. The three main use cases are: collision avoidance (two properties named body from different objects), API bridge patterns (snake_case to camelCase at the destructuring site), and clarity improvements (renaming generic names like value to inputValue). For the full powerful set of destructuring patterns, see advanced array and object destructuring guide.
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.