0
0
JavascriptHow-ToBeginner · 3 min read

How to Rename Variables in Destructuring in JavaScript

In JavaScript, you can rename variables during destructuring by using the syntax { originalName: newName } for objects and [originalName: newName] is not valid for arrays. For objects, this lets you extract a property and assign it to a new variable name in one step.
📐

Syntax

When destructuring an object, you can rename variables by specifying the original property name followed by a colon and the new variable name.

  • { originalName: newName } extracts the property originalName and assigns it to a variable called newName.
  • This does not change the original object, only the variable name used in your code.
javascript
const { originalName: newName } = object;
💻

Example

This example shows how to rename variables when destructuring an object. The property firstName is extracted and renamed to name.

javascript
const person = { firstName: 'Alice', age: 25 };
const { firstName: name, age } = person;
console.log(name); // Alice
console.log(age);  // 25
Output
Alice 25
⚠️

Common Pitfalls

One common mistake is trying to rename variables when destructuring arrays using the same syntax as objects, which is not valid.

Also, forgetting the colon : between the original property and new variable name will cause syntax errors.

javascript
const arr = [1, 2, 3];
// Wrong: const [0: first] = arr; // SyntaxError

// Correct way to rename array elements is to assign after destructuring:
const [first] = arr;
console.log(first); // 1
Output
1
📊

Quick Reference

Destructuring TypeSyntax to Rename VariableExample
Object{ originalName: newName }const { firstName: name } = person;
ArrayNo direct rename syntaxconst [first] = arr; // assign new variable name directly

Key Takeaways

Use { originalName: newName } syntax to rename variables when destructuring objects.
You cannot rename variables directly when destructuring arrays; assign new variable names normally.
Always include the colon ':' between the original property and new variable name to avoid syntax errors.
Renaming variables does not change the original object or array, only your local variable names.
For arrays, destructure by position and assign variable names directly without renaming syntax.