Use JavaScript Array Destructing to Name Array Indexes

Will Johnson
InstructorWill Johnson

Share this video with your friends

Send Tweet
Published a year ago
Updated a year ago

You can use array destructing to access values like string and functions and give them names your prefer without using bracket notation.

Instructor: [0:01] We have an array called cars with three items inside of it. If I want to access those items in the array, I will use bracket notation. Cars zero, would give me the first item. If I type in NodeCars.js, it will give me Corvette which is the first item in the array.

[0:22] If I want to add the second item hit, cars one, go to the terminal, NodeCars.js and that will give me the second item in the array. Let's say I don't want to use bracket notation. I want to give these values names. I can do that with array destructuring.

[0:43] If I wanted to access the first item, and you can name it whatever you want. Doesn't have to be first, but I'm going to use the name first here. Once we go here, we put first in the console.log. We run NodeCars.js and now we get Corvette.

[1:01] If I want to get the second item. Add second to the console.log. Keep in mind you can name these anything. I'm just using first and second as placeholders. Save that, and then use NodeCars.js, and now you get the second item which is Camaro.

[1:24] Let's say I only want the last item in the array which is Mustang and I don't want the other values. I can use, ,,last. Hit save. Goes to our console.log, hit last, save. Then NodeCars.js will give us Mustang.

[1:45] If you want to skip any items in the array and only give a certain one a name, you can use commas as placeholders. Now arrays can be other values outside of strings and things like that. I'm going to paste in a function here as a second item.

[2:04] A function called sum, that's going to take in a non-parameter and then return the value of num plus num. If I want to get access to that, I would use a comma as a placeholder. Then name the function, add.

[2:21] Then, here I'm going to call add, parse in two, and then NodeCars.js. Now we get the value of four which is two plus two. To recap, we can use array destructuring to pull values out of our arrays and give them names that we prefer. We can access them by name instead of using bracket notation.