DEV Community

Ndonna
Ndonna

Posted on

DESTRUCTURING ARRAYS IN JS

Hi I am Ndonna Ugwuede a javaScript newbie, and as a noob in javaScript i found it hard understanding Destructuring, even after reading many materials and watching tutorial videos it was still sounding strange but thanks to Mark Zamoyta i finally got a grasp of it.

Firstly, what do you need destructuring for?

Destructuring gives us an avenue to name our Array/Object items as against the regular calling of array items with "arrayName[0]" or Objects with "object.key".

DESTRUCTURING ARRAYS

You can destructure an array using the syntax let [name1, name2, name3] = names; where names is an already existing array. Using an example we have an array named Cars with content ["Benz", "Honda", "Nissan", "Toyota", "Ford"] and we want to assign them to variables namely car1, car2, car3, car4, car5. Going the old school way we would to go through assigning each with:
let car1 = Cars[0], car2 = Cars[1], .... etc
Alt Text

Destructuring has brought a simpler way to do this where you can name array items where we can name our array items using:
let [car1, car2, car3, car4, car5] = Cars;
Alt Text

You could even assign the remaining items into another named array using a rest operator (...), if we aren't sure of the number of items to be named.
Alt Text

Another beauty is we could skip some items, if we are sure of what to skip, some strategic items we are sure of we could be removed by putting a comma in its place e.g we could remove our first and second item of the array using:
let [,,car3, car4, car5] = Cars;
Alt Text

Destructuring also works fine with/on Objects, I'll be making another post explaining DESTRUCTURING OBJECTS IN JS, in the near future but in the meantime you could reach out to me on twitter: https://twitter.com/Ndonnauc

Top comments (1)

Collapse
 
iambenkay profile image
B_aaS

Wow! I didn't know about the skip feature!

Thats new. I'll try it out! 🔥🔥