How to use forEach in JavaScript

Learn how to use forEach, how it differs from for loops and map, and when you should/shouldn’t use it

Sunil Sandhu
Jan 26, 2019 · 2 min read
Image for post
Image for post

If you’ve spent a bit of time around any programming language, you’ve likely come across a ‘for loop’. For loops are super useful, but they can sometimes be a bit fiddly to write. I remember it being one of the first programming concepts I had come across, and it took me quite a long time to be able to memorise. It took me an even longer time to realise that there was a simpler way to write these in Javascript — the easier way being forEach.

Okay, but what’s the difference?

The difference between a for loop and a forEach is that, in a for loop, you decide how many times you want the function to run, whereas a forEach loop will run as many times as there are items inside of the array that it is being used on.

For example, if there are three items in an array, the forEach will run three times — once on each item in the array. Whereas with a for loop, you will need to tell it to run three times. That sounded a little bit complicating, so let’s take a look at how we would write the same function using both a for loop and a forEach:

For:

const animals = [‘cat’, ‘dog’, ‘sunny’];
const copy = [];

ForEach:

const animals = [‘cat’, ‘dog’, ‘sunny’];
const copy = [];

So here, animals.forEach(function(animal) is the same as for(let i=0; i<animals.length; i++).

You can even choose to make your forEach even more concise by using ES2015 syntax, as such:

const animals = [‘cat’, ‘dog’, ‘sunny’];
const copy = [];

The key thing to remember here though is that a forEach is useful when you are planning on running the same function on every item in an array. But if you need to write something a bit more bespoke and customisable, a for loop may be a better solution.

I hope you have found this super short tutorial useful. If so, be sure to leave plenty of claps!

JavaScript In Plain English

New articles every day.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store