Rewrite Your Own Array Methods: forEach, map, filter, find, and reduce

Nguyễn Quyết
Jul 23 · 3 min read

Get a better understanding of these JavaScript methods

Many of my students were struggling to understand how these functions work and I see the same issue with many junior developers that are new to JavaScript.

So, I decided to rewrite these functions in the hope that it will help them get a better understanding of these methods.

To use array methods, you can have a look at a previous piece I wrote.


forEach

The arr.forEach method allows you to run a function for every element of the array. forEach doesn’t return anything.

Rewrite for use with the for loop:

Test it on the Chrome console:

See, the result is exactly the same.

So, basically, the forEach function implements a for loop inside it.

We can also make myForeach better by adding it in the array prototype chain and use it as a normal forEach function.

Done! And, we can use something like this ['a','b',c'].myForeach(...).

With the same approach, we can rewrite map find filter reduce with a for loop.


map

The map function always returns the new array with the same length as the original.


find

The find function returns the first item that matches the callback function, or undefined if there is nothing that matches.


filter

This works like the find function, but instead of returning the first matched item, filter will return the array of matched items or an empty array if nothing matched.


reduce

Instead of returning an array, such as map or filter, reduce returns any value we want. We only need to pass the initial value, then modify it over each iterator.


Conclusion

Note that this is not an actual implementation of these function in JavaScript. It’s just another, similar approach to determine how it works, equivalent to using the for loop for better understanding how it works under the hood.

The .sort function is not mentioned in this article because it deserves its own post which I will try to write soon.

Thanks for reading.

Better Programming

Advice for programmers.

Nguyễn Quyết

Written by

javascrip lover

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade