Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Aliasing destructured variables in JavaScript

Here’s a little tip that I learned recently. It’s about destructuring an object and aliasing the destructured variables. I’ll show you how it works with an example.

Let’s say we have an object like this.

const User = {
    name: 'John Doe',
    age: 30
};

Now, if we want to destructure the object to get the name and age properties, we can do something like this.

const { name, age } = User;

console.log(name); // John Doe
console.log(age); // 30

As you can tell, when we destructure the object, it’s important to note that the variable names that we use to destructure the object must match the property names of the object.

Aliasing destructured variables

But, what if we want to alias the variables to something else? For example, we want to alias the name variable to fullName and the age variable to userAge.

Here’s what we can do.

const User = {
    name: 'John Doe',
    age: 30
};

const { name: fullName, age: userAge } = User;

console.log(fullName); // John Doe
console.log(userAge); // 30

As you can tell, we can alias the variables by using the : operator. So, we can alias the name variable to fullName and the age variable to userAge.

Usefulness

This is pretty handy in scenarios where the destructured variables may conflict with other variables in the scope. So, we can alias them to something else to avoid conflicts.

This would also help in naming the variables in a more meaningful way and according to the context.

And that’s it! This is how we can alias destructured variables in JavaScript.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?