Super cool and Super helpful feature from ES6, even though it is a big topic 😂 I will try to make it short and easy
lets get started
Destructuring assignment
What is destructuring.
destructuring is used to break down complex structures into pieces. It's like unpacking a bag.
lets destucture with our first example
const obj ={
name:'bla bla',
car:'supra'
}
// Destructuring assignment
const { name } = obj // bla bla
though we can access the value like this alsoconsole.log(obj.name)
so what exactly is the point? the point is now we created a separate variable instead of array members. now we can directly access name wherever and whenever we want 🔥
some more powerful things we can do with destructuring.
let [name,lastname] = 'harshit paliwal'.split(' ')
console.log(name) //harshit
console.log(lastname) //paliwal
destructuring assignment works by copying an item into a variable. It doesn't modify the array its just a shorter way to write. same as
const arr = 'harshit paliwal'.split(' ')
console.log(arr[0]) //harshit
console.log(arr[1]) //paliwal
the variable we created is just a copy of obj/array if we change the value of the variable it doesn't affect the original object or array. we can reassign value whenever we want. 🔥
const obj = {
name:'harshit'
}
let {name} = obj;
name = 'jone'
console.log(name) // jone
There is a lot more than that we can do nested destructuring also
const obj = {
superHero: {
name: "iron man",
power: {
powerOne: 'rich',
powerTwo: 'super genius'
}
}
}
const {superHero:{name, power:{powerOne, powerTwo}}} = obj
console.log(name) //iron man
console.log(powerOne) //rich
console.log(powerTwo) //super genius
Conclusion
Destructuring is a powerful feature that can be used to make your code more readable and concise.
if you are not using it in your code I encourage you to give it a try. Happy coding
Top comments (0)