define new name while destructuring

Define New Name While Destructuring

When destructuring objects or arrays in JavaScript, it is often useful to rename the extracted properties or elements to new names for easier readability or to avoid naming conflicts. This can be done using the object or array destructuring syntax with the colon (:) operator followed by the new name.

Object Destructuring

Suppose we have an object called person with two properties: name and age. We can extract these properties and rename them as fullName and years respectively as follows:


const person = {name: 'John Doe', age: 30};
const {name: fullName, age: years} = person;

console.log(fullName); // 'John Doe'
console.log(years); // 30

The object destructuring syntax creates two new variables called fullName and years and assigns the values of the name and age properties of the person object to them respectively. We can then use these variables in our code instead of the original property names.

We can also use default values and nested properties while renaming, like so:


const person = {name: 'John Doe', age: 30, address: {city: 'New York', state: 'NY'}};
const {name: fullName, age: years, address: {city: hometown = 'Unknown'}} = person;

console.log(fullName); // 'John Doe'
console.log(years); // 30
console.log(hometown); // 'New York'

In this example, we extract the name, age, and address.city properties of the person object, and rename them as fullName, years, and hometown respectively. We also provide a default value of 'Unknown' for the hometown variable in case the address.city property is missing.

Array Destructuring

Similarly, we can rename elements while destructuring arrays using the same syntax:


const numbers = [1, 2, 3];
const [first: uno, second: dos, third: tres] = numbers;

console.log(uno); // 1
console.log(dos); // 2
console.log(tres); // 3

In this example, we rename the first, second, and third elements of the numbers array as uno, dos, and tres respectively.

We can also use rest parameters to extract the remaining elements of an array into a new array, like so:


const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;

console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]

In this example, we extract the first and second elements of the numbers array into separate variables, and the remaining elements are grouped into a new array called rest.

Overall, renaming properties or elements while destructuring objects or arrays can make our code more readable and avoid naming conflicts, especially when dealing with complex data structures.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe