What is object deconstruction in JavaScript?

What does "object destruction" mean, and what is the result of the destruction operation?

Suppose you have an object with certain properties:

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

You can extract some object properties and put them in named variables:

const { firstName, age } = person

Now we have 2 new variables,firstNamewithage, Which contains the required value:

console.log(firstName) // 'Tom'
console.log(age) // 54

The value assigned to the variable does not depend on the order in which we list them, but is based on the attribute name.

You can also automatically assign attributes to variables with other names:

const { firstName: name, age } = person

Now instead of one namedfirstName, Just like in the previous example, we have anamecontainperson.firstNamevalue:

console.log(name) // 'Tom'

Download mine for freeJavaScript beginner's manual


More js tutorials: