Rename variables while destructuring

In my last tutorial, I covered destructuring in JavaScript briefly. If you haven't know, what is destructuring and how to set default values while destructuring. Please check it out here

Before jumping on to renaming inside destructuring, we will see few of the cases when this is needed.

  • When the object returned from server doesn't have better key names. Example,
const obj = {
  prop1: 'Param',
  prop2: 26,
}

In the above snippet, nobody knows what is prop1 and prop2 without knowing the details of the backend. If we destructure and use the same variable, it will make the front end code unreadable and undebuggable later on.

  • When there is similar object props in two different objects. Example,
const obj1 = {
  name: 'Param',
  age: 26, // same key `age` present in obj2
}

const obj2 = {
  firstName: 'Ahmed',
  lastName: 'John',
  age: 29, // same key `age` present in obj1
}

Now, both the object have age key, we can't destructure both the variable as age. Instead, we need to rename either one of those.

Lets see how to do that,

for the example 1, this is how it can be destructured and renamed.

const { prop1: name, prop2: age } = obj
console.log(name, age) // Param, 26

for the example 2,

const { age: ageOfParam, ...restOfParam } = obj1
const { age: ageOfAhmed, ...restOfAhmed } = obj2

console.log(ageOfParam, ageOfAhmed) // 26, 29

Is in't it the syntax very easy to use? 😎

// Syntax

const { propKey: NewVariableName } = Object

Destructuring is very powerful in javascript, it has lot of use cases and make the developers life easier with several usecases.

Checkout the examples here,

https://codesandbox.io/s/rename-while-destructuring-6qrob

Beginners to ProNode Js

Visual Guide to API Design Best Practices

This visual eBook covers essential best practices for designing robust APIs using REST principles.

This book is ideal for beginners and backend developers seeking to enhance their API design skills. However, it is not suited for those seeking an in-depth exploration of API design. This book is a quick read under 40 slides like scrolling through your instagram feed.

Visual Guide to API Design Best Practices