DEV Community

Cover image for Old School Loops in JavaScript - for loop and forEach
Arbaoui Mehdi
Arbaoui Mehdi

Posted on

For Loop JavaScript Old School Loops in JavaScript - for loop and forEach

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

Top comments (11)

Collapse
 
genuinerex profile image
Rex Bloom

Breaking and returning from a for loop is tempting, but error prone. Using Functional techniques is a much better solution and leads to cleaner more testable code. Use .find to retrieve the first matching element. Closures are not a serious overhead concern that we should avoid them to conserve memory.

I agree with Michael, while loops should be avoided.

I personally cannot remember the last time I used while and for.

But to each their own. You have to maintain and read your code so write it however you want!

Collapse
 
mmikowski profile image
Michael S. Mikowski • Edited

Thanks for the post!

After using many loop techniques, I've simply reverted to 'for' loops for most purposes. They are simple and well understood, hardly more verbose, and perform better than forEach loops due to less memory use, less overhead (no closures!) and the ability to break. The first two benefits are relatively small, but the ability to cleanly break out of a large collection on a first match can make a big difference.

Btw, IMO, always use 'for' loops instead of 'while' loops. The latter are very prone to becoming endless loops when logic changes. I've removed all while loops from all my recent code for this reason.

There are instances where forEach style closures make sense when running async code. But even then, it sure would be better to have jQuery 'each' behavior which actually worked (e.g. returning false did break the loop).

Collapse
 
emertola profile image
emertola

I'm fascinated with your editor. what do you use?

Collapse
 
arbaoui_mehdi profile image
Arbaoui Mehdi

I'm using VSCode as an Editor, plus Quokka as an extension that shows the live results of the console.log

Collapse
 
josemoreira profile image
JosΓ© Moreira

what is your theme?

Thread Thread
 
arbaoui_mehdi profile image
Arbaoui Mehdi
Collapse
 
emertola profile image
emertola

Awesome. Will install that one. Thanks

Collapse
 
learnwithparam profile image
Paramanantham Harrison

What theme is this? It’s looks nice.
How do you record this gif/video?

Collapse
 
arbaoui_mehdi profile image
Arbaoui Mehdi

The theme I'm using is Cobalt2 Theme for VS Code, and for creating GIFs I'm using Screenflow for creating first the screencast, then I export it to gif.

Collapse
 
andrewbrown profile image
Andrew Brown πŸ‡¨πŸ‡¦

It appears you are using Wallby.js
I have rarely seen anyone use it but I think it is cool. Sadly it's not compatible with MacVim.

I would love to hear your day to day experience with it.

Collapse
 
arbaoui_mehdi profile image
Arbaoui Mehdi

To be honest I'm not using a lot in my day to day work, except if I'm creating a video tutorial or if I'm playing with data structures for a specific problem.