简体   繁体   中英

Best practice: Javascript for loop

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?

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.

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())

Or if you need to iterate from back to front:

 for(const el of array.reverse())

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(var len = lenArr; len > 0; len--){
        for(var len2 = lenArr2; len2 > 0; len2--){
            //dostuff
            if (exitCondition) return;
        }
    }
}

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    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM