DESTRUCTURING

Destructuring

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables.

Array destructuring :

We should have an existing array at the right side, that we want to split into variables. The left side contains an array-like “pattern” for corresponding elements. It is shorter way of copying array items in to variables.

Example :

const fruits = ["Orange", "Banana", "Lemon"]
// we can access each element of an array by their index.
const fruit1 = fruits[0]
//or else we can use destructuring to get those elements without using indexes
const [first, second] = fruits
console.log(first, second) //Prints: Orange Banana

Object destructuring :

We should have an existing object at the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. Here, order does not matter but key name should be same as in the object.

Example :

const amir = {
first: 'amir',
last: 'khan',
city: 'mumbai'
}
// we can access each value of an object by their keys as shown below.
const firstName = amir.first;
const lastName = amir.last;
// or else we can use destructuring to get those values
const {first, last} = amir
console.log(first, last) //Prints: amir khan