Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 666
Daniel Bengtsson Avatar asked Apr 13 '18 05:04

Daniel Bengtsson


People also ask

Which is more efficient for loop or while loop in JavaScript?

In theory the while loop is quicker because the for loop looks up the length attribute of foo every time though the loop, but in real-world use it's going to make an immeasurably small difference. Save this answer.

Is for loop faster than filter JavaScript?

To our surprise, for-loops are much faster than the Array. filter method. To be precise, the Filter method is 77% slower than for loop.


2 Answers

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.

like image 60
Pranay Rana Avatar answered Sep 24 '22 05:09

Pranay Rana


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;
        }
    }
}
like image 29
trincot Avatar answered Sep 22 '22 05:09

trincot