Home:ALL Converter>Best practice: Javascript for loop

Best practice: Javascript for loop

Ask Time:2018-04-13T13:00:06         Author:Daniel Bengtsson

Json Formatter

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?

Author:Daniel Bengtsson,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/49809601/best-practice-javascript-for-loop
Pranay Rana :

IF you have array than make use of forEach \n\narray.forEach(ele=> {\n\n});\n\n\nthat way you can keep code clean and easy to understand and dont have to do length related code.\n\nBreak is not going to work with forEach but you can write return for coming out of forEach like \n\narray.forEach(ele=> {\n ele.array.forEach(ele=> {\n //do stuff \n return;\n });\n});\n\n\nNote: \n\n\nfor loop is faster.\nforEach is slower, but better fits functional programming paradigms.\n\n\nAnswer is based on title of question : Best Practice that why given suggestion to make use of forEach over for. ",
2018-04-13T05:03:06
Jonas Wilms :

Actually, i prefer for...of as you can still break and its much less typing and its definetly more readable:\n\n for(const el of array)\n\n\nIf you need indices too:\n\n for(const [index, el] of array.entries())\n\n\nOr if you need to iterate from back to front:\n\n for(const el of array.reverse())\n",
2018-04-13T05:19:15
trincot :

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.\nIterating 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.\nAs 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.\nSo 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.\nIf you want to exit quickly from nested loops, then consider placing them in a function, so you can use return:\nfunction performNestedLoop(array, array2) {\n for(let i = 0; i < array.length; i++){\n for(var j = 0; j < array2.length; j++){\n //dostuff\n if (exitCondition) return;\n }\n }\n}\n\nAs 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.",
2019-12-28T19:06:06
yy