Destructuring In Javascript
It is a way to extract data from arrays or objects into distinct variables.
ES6 provides a new feature called destructuring assignment that makes it easy to assign array values and object properties to distinct variables.
Array Destructuring in javscript
It allows you to extract an array’s values into new variables.
For example,
1.without using array destructuring
const languages=["HTML5","CSS","Javascript","Python"];
const l1= languages[0];
const l2= languages[1];
console.log(l1);
console.log(l2);
/*
Output - HTML5
CSS
*/
2. Using array destructuring
const languages = [ "HTML5", "CSS", "JavaScript", "Python"];
// array destructuring
let [languagel, language2, language3, language4] = languages;
console.log("The first programming language is: "language1);
console.log("The second programming language is: " language2);
Output - The first programming language is: HTML5
The second programming language is: CSS
3. Array destructuring with spread operator
const languages = [ "HTML5", "CSS", "JavaScript", "Python"];
const [languagel, language2 , ...otherlanguages] = languages
console.log(language1) // Output - HTML5
console.log(otherlanguages) // Output - [CSS, Javascript, Python]
Object Destructuring in Javascript
It allows you to extract an object’s value into new variables.
For Example
1. Without using object destructuring
const detail ={
firstname:"john",
Lastname:"doe",
email:"johndoe@gmail.com"
}
console.log(detail.firstname) // Output - John
console.log(detail.lastname) // Output - doe
console.log(detail.email) // Output - johndoe@gmail.com
2. Using object destructuring
const detail = {
firstname:"john",
Lastname:"doe",
email:"johndoe@gmail.com"
}
// object destructuring
let {firstname, lastname, email} = detail
console.log(firstname) // Output - john
console.log(lastname) // Output - doe
console.log(email) // Output - johndoe@gmail.com
3. Another example of using object destructuring
const {fname, Iname, ename} ={
fname:'john',
Lname:'doe',
ename:'john@doe.com'
}
console.log(fname) // Output - john
console.log(ename) // Output - john@doe.com