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];
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]);
}
The result of console.log
shows an element from the list numbers
at a specific index
using the counter.
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);
});
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);
});
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);
});
Top comments (11)
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!
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).
I'm fascinated with your editor. what do you use?
I'm using VSCode as an Editor, plus Quokka as an extension that shows the live results of the
console.log
what is your theme?
I'm using Cobalt2 Theme for VS Code
Awesome. Will install that one. Thanks
What theme is this? It’s looks nice.
How do you record this gif/video?
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.
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.
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.