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.

JavaScriptintermediate
9 min read

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:

javascriptjavascript
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 variables

The colon in destructuring means "rename to", not a value assignment.

When to Use Renaming

Avoiding Name Collisions

javascriptjavascript
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:

javascriptjavascript
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

javascriptjavascript
const { value: inputValue } = document.getElementById("search");
// More descriptive than just 'value' — clarifies it comes from the input element

Combining Renaming With Default Values

To both rename and provide a default, the syntax is { property: newName = defaultValue }:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
// 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:

javascriptjavascript
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 named

If you want to "rename" from a destructured array, you simply write whatever name you want.

Comparison: With and Without Renaming

PatternHow It Works
const { a } = objExtracts obj.a into variable a
const { a: b } = objExtracts obj.a into variable b
const { a = 10 } = objExtracts obj.a into a; default 10 if obj.a is undefined
const { a: b = 10 } = objExtracts obj.a into b; default 10 if obj.a is undefined
const { a: { b } } = objNested: extracts obj.a.b into b
const { a: { b: c } } = objNested + rename: extracts obj.a.b into c

Practical Pattern: API Response Normalization

javascriptjavascript
// 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

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
RunePowered by Rune AI

Frequently Asked Questions

Does renaming affect the original object?

No. Destructuring creates new local variable bindings. The original object's property names are unchanged.

Can I use the same name for renamed and non-renamed properties in the same destructure?

Yes: `const { a, b: c } = obj` extracts `a` as `a` and `b` as `c`. You can mix freely in one destructuring statement.

What if I want to rename and use rest?

`const { a: alias, ...rest } = obj` — aliases `a` to `alias` and collects all other properties in `rest`. This is valid and useful for omitting a field after aliasing it.

Is there a way to do this with computed property names?

Yes. `const { [dynamicKey]: aliasName } = obj` — extracts the property whose key equals `dynamicKey`'s value and names it `aliasName`. ```javascript const key = "color"; const { [key]: extractedColor } = { color: "red" }; // extractedColor = "red" ```

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.