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.

JavaScriptbeginner
11 min read

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:

javascriptjavascript
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

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

javascriptjavascript
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

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

javascriptjavascript
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 HappensExampleResult
Property exists{ a: x = 5 } where a is 10x = 10
Property is undefined{ a: x = 5 } where a is undefinedx = 5
Property missing{ a: x = 5 } where no ax = 5
Property is null{ a: x = 5 } where a is nullx = null (default NOT applied)
Property is 0 or ""{ a: x = 5 } where a is 0x = 0 (default NOT applied)

Defaults only trigger for undefined, not for other falsy values.

Nested Object Renaming

Rename properties inside nested objects:

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

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

API Data Processing Pipeline

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

javascriptjavascript
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

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

Common Mistakes to Avoid

Confusing Rename Direction

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

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

Frequently Asked Questions

Can I rename and set a default at the same time?

Yes. Use the syntax `{ propertyName: newVariable = defaultValue }`. For example, `{ bg_color: backgroundColor = "#fff" }` renames `bg_color` to `backgroundColor` and provides `"#fff"` as the default if the property is missing or `undefined`.

Does renaming create a new copy of the value?

For [primitive values](/tutorials/programming-languages/javascript/primitive-vs-reference-types-in-js-full-guide) (strings, numbers, booleans), yes, the new variable holds an independent copy. For reference values (objects, [arrays](/tutorials/programming-languages/javascript/what-is-an-array-in-javascript-a-complete-guide)), the new variable points to the same reference. Modifying the destructured object will affect the original and vice versa.

Is there a performance difference between renaming and direct destructuring?

No. JavaScript engines compile both patterns to equivalent property access operations. The colon syntax is purely a source-code convenience. There is zero runtime difference between `const { name } = obj` and `const { name: userName } = obj`.

Can I use computed property names with renaming?

Yes. Use bracket notation on the left side: `const { [dynamicKey]: localVar } = obj`. This extracts the property whose name is stored in `dynamicKey` and assigns it to `localVar`.

How do I handle multiple APIs with different naming conventions?

Create a transformer function for each API that destructures and renames properties to your internal convention. Call this transformer at the API boundary (right after fetching) so the rest of your codebase works with consistent [camelCase](/tutorials/programming-languages/javascript/javascript-variable-naming-conventions-and-rules) names.

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.