The Destructuring Assignment is a JavaScript expression.
Destructuring Assignment 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.
Example 1: Creating an object with key value and pair an taking an array as pair value of key
var obj1 = {
key1:'value1',
key2:'value2',
key3:'value3',
key4:['Array Element 1','Array Element 2', 'Array Element 3']
}
console.log(obj1)
console.log(obj1.key1) //value1
console.log(obj1.key2) //value2
console.log(obj1.key3) //value3
console.log(obj1.key4) //[ 'Array Element 1', 'Array Element 2', 'Array Element 3' ]
// using only 2 key:value from obj1
var {key1,key2} = obj1
console.log(key1) //value1
console.log(key2) //value2
console.log(key3) //Not define ReferenceError
// here key3 is not taking as variable using the obj1 so this will show error
//finally we can see that we can show what we want form the various key:value of any object
// using obj1 key and reassigning
var {key1,key2,key3} = obj1
var key1 = 'New value1'
var key2 = 'New value2'
var key3 = 'New value2'
console.log(key1) //New value1
console.log(key2) //New value2
console.log(key3) //New value3
// iterating all values of key4 which is the key of obj1
for (var i = 0; i<obj1.key4.length; i++){
console.log(obj1.key4[i])
}
//////////////////////////////////////////////////////////
// incoming function arguments Destructing
var lordL = regPerson =>{
return(`${regPerson.fn} ${regPerson.ln} of MM(DU)`)
}
var regPerson = {
fn: 'Sam',
ln:'Edware'
}
console.log(lordL(regPerson))
//////////////////////////////////////////////////////////
// values destruct from the arrays
var [arr1] = ['el11','el12','el13']
var [,arr2] = ['el21','el22','el23']
var [,,arr3] = ['el31','el23','el33']
console.log(arr1)
console.log(arr2)
console.log(arr3)
// arr1 has no any comma then this will paa first value only
// arr2 has one comma in the starting then the value pss second of arr2 only
// as the arr3 is the third of this state then it will pass the third value only