For each loop in javascript

The forEach Loop in JavaScript: Explained.

If you are studying Web Development you will come across Arrays pretty early on. Once you come to that point, you will need to learn and understand the forEach loop in Javascript. I still consider myself a beginner at Web Development, but I try to break things down to understand them better. Today we are going to look at the forEach Loop in JavaScript.

Why do you need the forEach Loop in JavaScript?

There are two ways to loop through an Array. You can loop through an Array with a simple for loop:

const testArray = ["Item 1", "Item 2", "Item 3"]

for(let i = 0; i < todos.length; i++) {
    console.log(todos[i])
}

This will return the following:

Item 1
Item 2
Item 3

This is quite a bit of code that we can shorten using a forEach loop:

const testArray = ["Item 1", "Item 2", "Item 3"];

testArray.forEach(function(item) {
  console.log(item);
});

This will return the following:

Item 1 
Item 2 
Item 3

As you can see, the code for the forEach loop is much easier to read than the code for the for loop. But let’s break it down.

The forEach Loop in JavaScript explained

I try my best to make it as easy as possible.

The forEach loop is a pre-defined Array Method. We can use forEach to iterate through an Array and return certain values. forEach can only be used on Arrays, Sets, and Maps. The forEach loop takes a so-called Callback Function, in our case this function is called item. This Callback function runs once for every element in the array in ascending order. But you can call this Callback function whatever you want, let me demonstrate it.

const testArray = ["Item 1", "Item 2", "Item 3"];

testArray.forEach(function(hotDog) {
  console.log(hotDog);
});

We changed the item Callback function to hotDog, the output stays the same:

Item 1
Item 2
Item 3

There are also other arguments this function can take like index, array, and thisArg.

  • index – returns the index position of the array item
  • array – defines the array forEach() was called on
  • thisArg – A value to use this with the callback

An example of the index argument would be:

const testArray = ["Item 1", "Item 2", "Item 3"];

testArray.forEach(function(index, hotDog) {
  console.log(index);
  console.log(hotDog);
});

Which would return:

Item 1
0
Item 2
1
Item 3
2

So it shows you the index of the item inside of the array after each array item.

Conclusion

There are, of course, more things you can do with forEach, but this should cover the basics and give you a solid foundation on the forEach method. I highly recommend checking out MDN and play around with the forEach loop in JavaScript to get a better understanding of it.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: