Introduction

In JavaScript, object destructuring is a powerful feature that allows you to extract specific properties from an object and assign them to individual variables. This can make your code more concise and readable by eliminating the need for repetitive object property access.

How Object Destructuring Works

Consider the following example:

const person = {
  firstName: 'Tom',
  lastName: 'Cruise',
  actor: true,
  age: 57
};

To extract specific properties from the person object and assign them to variables, you can use object destructuring:

const { firstName, age } = person;

In this case, the firstName and age variables will be created and assigned the values of the corresponding properties from the person object:

console.log(firstName); // 'Tom'
console.log(age); // 57

The order in which the variables are listed doesn’t matter. The assignment is based on the property names.

Renaming Variables

You can also assign object properties to variables with different names using object destructuring. This can be useful when you want to give variables more meaningful names or avoid naming conflicts:

const { firstName: name, age } = person;

Now, instead of a variable named firstName as in the previous example, we have a name variable that holds the value of the person.firstName property:

console.log(name); // 'Tom'

Conclusion

Object destructuring in JavaScript allows you to extract specific properties from an object and assign them to individual variables. By mastering this feature, you can write more concise and readable code.