DEV Community

YoonSL
YoonSL

Posted on

Foreach array loop breakdown

Hello guys, I am still a beginner in using JavaScript, but I am here to share one of the hardest problem my colleagues and I have encountered while learning JavaScript. Foreach array looping is not one of the hardest method, but was one of the hardest method to get in to habit. Since we have learned for loop before foreach array loop and everything, I think, could have been done the same without using foreach array loop.

Here is a simple example on for loop:

alt text

The output of the console log for loop is:

alt text

Also, this is a simple example on Foreach loop is:

alt text

The output of the console log for Foreach loop is:

alt text

If you take a look at both examples, way the code is written is different but both of the loops have the same output.

So, in theory, exampleArray.forEach method is equal to for(let i=0; i < exampleArray.length;i++) and the function inside the forloop is equal to function inside the forEach loop.

alt text

Ob-course we know there are no variable i in foreach loop so to create methods using the variable i it would be better to use forloop.

Here is another example including the if statement inside a forloop:

alt text

And a example of foreach loop with if statement:

alt text

In this examples, if statements are included in both of the forloop and foreach loop. In the forloop example, the array is represented using array variable name followed by a bracket. The i in bracket is a number that represents the position of the currently selected array. The for loop checks if the array is smaller then three and adds three if true and does nothing to the array if false. In the foreach example, number represents each of the array in order and it checks if the number in array 0 or 1 is smaller than the value of 3 and adds values of 3 if the number in each of the array is smaller then 3. So the upside for using forloop is array can be picked out with the pointer, but the downside would be that the code is much longer and messer.

Top comments (0)