6289910425190400

What is Object Destruction in JavaScript?

Object destruction is a very useful concept in JavaScript. We can save values from an object inside variables.

let { firstName, lastName } = { firstName: 'Harper', lastName: 'Johnson' }
console.log(firstName)
console.log(lastName)

We can also destruct in some other variable name of our own will. 

let { firstName: first_name, lastName } = { firstName: 'Harper', lastName: 'Johnson' }
console.log(first_name)
console.log(lastName)

We can destruct object in a variable and copy it into another object at the very same time. 

let {firstName, ...otherNames} = {firstName: 'Harper', middleName: 'Kevin', lastName: 'Johnson'}
console.log(firstName)
console.log(otherNames)

We can destruct an array inside an object too.

const data = { arr: [ 1, 2, 3 ] };
const { arr: [ v1, v2, v3 ] } = data;
console.log( v1, v2, v3 );

I hope these examples will add something new to your JS knowledge.