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

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 = [];
for (let i=0; i<animals.length; i++) {
copy.push(animals[I])
}

ForEach:

const animals = [‘cat’, ‘dog’, ‘sunny’];
const copy = [];
animals.forEach(function(animal){
copy.push(animal)
});

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 = [];
animals.forEach(animal => { copy.push(animal) });

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!