Array Object de-structuring

Create variables by extracting data from array or object using de-structuring javascript expression.

Example :

// array example
const [a, b] = [10, 20]; 
console.log(a);
// output: 10
console.log(b);
// output: 20

// object Example 
const { first_name, last_name } = { 
     first_name: 'Amol', 
     last_name : 'V' 
};
console.log(first_name); 
// output : 'Amol'
console.log(last_name); 
// output : 'V'

Along with this we can set default values to variables, can ignore some values in array, swap variables in single lines.

Using rest operator (…) we can split array if required.

const { rollNo, ...studentDetails } = {
rollNo : 123,
name : 'Amol',
subjects : ['Physics', 'Mathematics', 'Biology'], 
extras : ''
}

console.log( rollNo );
// output : 123
console.log( studentDetails );
// output : {
//    name : 'Amol',
//    subjects : ['Physics', 'Mathematics', 'Biology'], 
//    extras : ''
// }

Important : Rest operator should be used as last element in array or object.

Leave a comment

Your email address will not be published. Required fields are marked *