Minds
It is Recommended to practice while you learn

Destructing operator

Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables. In Destructuring Assignment on the left-hand side defined that which value should be unpacked from the sourced variable.

Traditional Way



let array1= [1, 2, 3, 4, 5];

console.log(array1[0]);
console.log(array1[1]);
console.log(array1[2]);
console.log(array1[3]);
console.log(array1[4]);

By Destructing operator



let array1 = [1, 2, 3, 4, 5];


let [ indexOne, indexTwo, indexThree, indexFour, indexFive ] = array1;

console.log(indexOne) // output : 1
console.log(indexTwo) // output : 2
console.log(indexThree) // output : 3
console.log(indexFour) // output : 4
console.log(indexFive) // output : 5


// if we want to skip one element

let [ indexOne, indexTwo, , indexFour, indexFive ] = array1;

console.log(indexOne) // output : 1
console.log(indexTwo) // output : 2
console.log(indexFour) // output : 4
console.log(indexFive) // output : 5


Object destructuring :

Example 1 :


({ x, y} = { x: 10, y: 20 });
console.log(x); // 10
console.log(y); // 20



Example 2 :


let object = {
name: "Nishant",
age: 24,
height: '20 meters',
weight: '70 KG'
}

let { name, salary, weight } = object;

console.log(name)
console.log(salary)
console.log(weight)


Spread operator

The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array. spread operator in JavaScript is denoted by three dots.

Traditional Way



let array1 = [1, 2, 3, 4, 5]
let array2 = [6, 7, 8, 9, 10]

let array3 = array1.concat(array2);
console.log(array3)

By Destructing operator



Example 1 :

let array1 = [1, 2, 3, 4, 5]
let array2 = [6, 7, 8, 9, 10]

let array3 = [...array1, ...array2]
console.log(array3)



Example 2 :

let array1 = [1, 2, 3, 4, 5]
let array2 = [6, 7, ...array1, 8, 9, 10]

console.log(array2);



Example 3 :

let object1 = {
firstName: "Nishant",
age: 24,
salary: 300,
}

let object2 = {
lastName: "Kumar",
height: '20 meters',
weight: '70 KG'
}

let object3 = ...object1, ...object2
console.log(object3);