Old School Loops in JavaScript - for loop and forEach

Arbaoui Mehdi - Oct 2 '19 - - Dev Community

In general, if we've got a list of elements, and we want to get each element from this list, or in other words if we want to iterate over the elements of an array we use the old-style for loop.

for Loop

As an example, we've got here an array numbers that contain a list of numbers.

const numbers = [45, 78, 95, 36, 47];
Enter fullscreen mode Exit fullscreen mode

To get each number from this array by using the for loop, first we've initialize the counter to 0, the condition to be evaluated before each iteration, and the expression to be evaluated after each iteration, in this case incrementing the counter by one, and as long as the condition is true

for (let i = 0; i < numbers.length; i += 1) {
 console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

The result of console.log shows an element from the list numbers at a specific index using the counter.

for loop JavaScript

forEach

Now, and for the same example, we can use the JavaScript ES5 forEach loop, which executes a function on each element in the array.

numbers.forEach(number => {
 console.log(number);
});
Enter fullscreen mode Exit fullscreen mode

forEach loop

Just to notice that the forEach is used only for arrays, maps, and sets, the syntax of the forEach is shorter than the for loop, however, there are some flaws of using it.

The first problem is there is no way to break or stop a current loop, this current presentation is not correct.

numbers.forEach(number => {
 if (number == 45) {
   console.log("terminate the current loop");
   break;
 }
 console.log(number);
});
Enter fullscreen mode Exit fullscreen mode

JavaScript forEach Loop can't Break

The second problem is: you can't use the return statement from an enclosing function within the loop, and this is an example where the loop should stop and return false if the condition is true, but instead it'll show the result of the console.log(number).

numbers.forEach(number => {
 if (number == 45) {
   console.log("terminate the current loop");
   return false;
 }
 console.log(number);
});
Enter fullscreen mode Exit fullscreen mode

JavaScript forEach Loop return statement

. . . . . . . . . . . . . . . . . . .
Terabox Video Player