DEV Community

Kyle Trahan
Kyle Trahan

Posted on • Updated on

Javascript Array Properties and Methods

I'll be going over the length/size property and a couple methods involving removing/adding an index/indexes to an array.

One of the most commonly used properties of a Javascript array is .length. This property when called on an array will return to you the amount of items inside your list. This is extremely helpful when it comes time to iterate through your list. It is commonly used to set the condition upon which your loop will stop running.

You can also use the length method to clear the array out. If you set the array.length = 0. You can also set the value of your index by doing array[index] = value. This can be dangerous however because you could end up leaving empty values on all the indexes between the one you are setting and the last one you set. It's one of the downfalls of arrays being so versatile. It's better to use the built in methods for arrays rather than treating them like a normal Javascript Object.

This leads me to the first few methods I am going to discuss. Those being .push(), .pop(), .shift(), and .unshift(). First we will touch on .push() and .unshift() as they both add an item to an array.

The difference between .push() and .unshift() is rather small. They are invoked in the same way by calling the function on an array and then passing them the value/s that you want to add to your array. The biggest difference is that .unshift() will add the value to the beginning of your array and .push() will add the value to the end of the array.

The other two methods .pop(), and .shift() are very similar to their counter parts. Rather than add values to an array they will remove items from the array. With .pop() removing the last element and .shift() removing the first element.

These are some of the most commonly used methods for arrays whenever you first start learning about Javascript arrays. They all are considered to be mutating the array, which isn't always what you want to do! If you want to learn more about what I mean by mutating and ways to change your array non-mutating I will be doing another blog next week about that!

Top comments (2)

Collapse
 
jenbutondevto profile image
Jen

careful! .size isn't a native JS array method.

Some of my favourites are Array(n) and Array.fill, they're pretty niche, I don't think I have used them outside of unit testing..!

Collapse
 
ktrahan2 profile image
Kyle Trahan

Thanks Jen!