Monday, November 11, 2024

JavaScript object property alias

JavaScript object properties can be aliased using destructuring assignment with a custom variable name. This allows you to extract properties from an object and assign them to a new variable with a different name (alias) in a single step. Here’s how to do it:
const person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30
};

// Destructuring with aliasing
const { firstName: fName, lastName: lName } = person;

console.log(fName); // Output: John
console.log(lName); // Output: Doe
In this example, the properties firstName and lastName of the person object are aliased as fName and lName, respectively. Now, fName and lName hold the values of firstName and lastName without modifying the original object.

This technique is useful for creating shorter or context-specific names when working with object properties in your code.

No comments:

Post a Comment

Hot Topics