19

What is the best practice for writing a JavaScript for loop?

I started out writing it like this:

for(var i = 0; i < array.length; i++){
    //do stuff
}

But then I found that calculating the length on each pass is not ideal, so it should be more like:

var len = array.length;
for(var i = 0; i < len; i++){
    //do stuff
}

But then the loop is faster if you decrease rather than increase:

var lenArr = array.length - 1;
for(var len = lenArr; len > 0; len--){
    //do stuff
}

This kind of loop however doesn't really work if you want to break just one loop in a cluster of nested loops, so you should therefore get into the habit of using labels:

var lenArr = array.length - 1;
var lenArr2 = array2.length - 1;

loop1: for(var len = lenArr; len > 0; len--){
    loop2: for(var len2 = lenArr2; len2 > 0; len2--){
        //do stuff
        break loop2;
    }
}

Is there something else that will need to change, or is this the best practice for writing for loops in JavaScript?

6
  • 2
    Best practice IMO is to avoid for loops entirely whenever possible - unlike array methods, they require manual iteration, do not have any abstraction, have hoisting issues when newbie developers are using var, and are not composable. The Array methods are better in every respect except speed, and speed is rarely something to worry about unless you're writing a library. But this is opinion-based. Commented Apr 13, 2018 at 5:03
  • You can use jsperf.com to write tests to run these various scenarios against each other to check their performance. Occasionally the outcome will surprise you and the browser makers will have optimized certain paths to be faster than others. Commented Apr 13, 2018 at 5:04
  • break loop2; ... that looks like awful code Commented Apr 13, 2018 at 5:09
  • I did this kind of quick, but it looks like, in Chrome anyways, a [for loop still beats forEach ](jsperf.com/for-vs-foreach-anied/1). That said, performance is one piece of the equation-- if your dataset is small and performance is not a critical factor, you can probably weigh readability a bit heavier on the scale... Commented Apr 13, 2018 at 5:13
  • 1
    if you want speed ... and you are dealing with large arrays ... don't use array native methods in Chrome or Edge (forEach etc) - they are mind numbingly slow - 93% and 98% slower respectively!! (as opposed to good browsers, where the difference is more like 3%) Commented Apr 13, 2018 at 5:15

4 Answers 4

10

IF you have array than make use of forEach

array.forEach(ele=> {

});

that way you can keep code clean and easy to understand and dont have to do length related code.

Break is not going to work with forEach but you can write return for coming out of forEach like

array.forEach(ele=> {
   ele.array.forEach(ele=> {
     //do stuff 
     return;
   });
});

Note:

  1. for loop is faster.
  2. forEach is slower, but better fits functional programming paradigms.

Answer is based on title of question : Best Practice that why given suggestion to make use of forEach over for.

Sign up to request clarification or add additional context in comments.

6 Comments

you may want to mention that you can't avoid looping through the whole array when using forEach ... i.e. there's no equivalent to break ... of course, you could use .some or .every instead
@JaromandaX - seems like modification to question let me go through i
Not really - he had the break stuff from the get go :p - all he's done is fix the "this is faster" code with code that actually enters the loop body :p
return does not break out of a forEach, it just stops the current iteration - it's like continue; in a for loop.
yep I use return inside foreach to "continue" the loop
|
7

Concerning saving array.length: Even though in the early days of JavaScript it made a difference to save the .length value in a variable, modern JavaScript engines will run the for loop just as fast if you write it as in the first version.

Iterating backward is also not guaranteed to run faster on modern engines. There is also the consideration that CPUs are optimised to anticipate forward memory references, although this will only be relevant when the JS engine has decided to store the array as a contiguous block of memory.

As for the use of labels: most would not consider this best practice. Where the previous optimisation (concerning .length) concerns all iterations of the loop, this issue only applies to a single exit out of both loops. Whatever solution you use, it represents constant time, and could not be a determining factor in the overall performance of the loop.

So certainly in this case, I would go with good coding habits over tiny optimisation considerations. When you want to exit just the current loop, a single break is enough.

If you want to exit quickly from nested loops, then consider placing them in a function, so you can use return:

function performNestedLoop(array, array2) {
    for(let i = 0; i < array.length; i++){
        for(var j = 0; j < array2.length; j++){
            //dostuff
            if (exitCondition) return;
        }
    }
}

As to best practice: this really depends on what you need to achieve. There are several array methods that provide iteration, like forEach, map, reduce, reduceRight, filter, some, every, find, findIndex, includes,... each with their purpose. If they fit the purpose, then go with them. If you don't need the index, but just the value, then use for..of. If you really need every speck of optimatisation, then the old fashioned for loop is a likely winner.

Comments

6

Actually, i prefer for...of as you can still break and its much less typing and its definetly more readable:

  for(const el of array)

If you need indices too:

  for(const [index, el] of array.entries())

1 Comment

Note that for (const el of array.reverse()) modifies the array array in place and that's probably not what one want in this case.
0

You can use Array.forEach

Advantage of using forEach are as follows

  1. Provides functional scoping, and whenever you need to perform some async function in the loop, you will not be required to created any IIFE
  2. It keeps your code tidy and more contextual

Sample Code

arr.forEach(function(item, index){
    // do stuff    
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.