JavaScript Array Methods

Marshall Slemp
3 min readOct 5, 2020

JavaScript gives us some built in methods to use on our arrays. We will cover the most used ones and give an example forEach(hint hint)… The methods all take a callback function as an argument and the method will call that function for every element in the array. Normally we would have to create for loops to iterate over our arrays, but now we can call these methods which keeps the code nice and clean!

forEach

Let’s start with the forEach method shall we! The forEach method allows us to iterate over each item in the array. You can see that we passed an arrow function in as the argument to forEach. The method will call that function and pass in the element as its argument. Inside our arrow function, we can do whatever we need to with each element, here we are simply logging each number to the console. The forEach will return undefined when its finished…keep this in mind!

The forEach method!

Map

Map is perhaps the most widely used method and for good reason. Map is similar to forEach except instead of returning undefined, it returns a new array. This array holds the values returned from the callback function we passed to it. In the example we are created a new array where each element is doubled. It does not mutate the original array! We must store the result of this method call in a variable so we can reference it later, otherwise we would lose the newly created array immediatly.

The Map method!

Filter

Filter is another widely used method for filtering (duh) items in an array. The filter method also returns a new array and does not mutate the original. For this method, the callback function needs to return true or false per element in the array. If the callback returns true the element will be put into the new array. If the callback function returns false, the element will not be put into the new array.

The Filter method!

And so much more…

These are not the only ones, we have sort, reduce, every, find and more! The 3 methods we covered are great a starting point and you should really focus on gaining a firm grasp of whats going on in these methods before moving on. A great place to learn more is MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#.

--

--