简体   繁体   中英

JavaScript loop best practice

I'm doing a tutorial on JavaScript . The following is from a section on performance:

Each statement in a loop, including the for statement, is executed for each iteration of the loop. Statements or assignments that can be placed outside the loop will make the loop run faster.

This is given as an example of bad code:

var i;
for (i = 0; i < arr.length; i++) {

And this is given as an example of good code:

var i;
var l = arr.length;
for (i = 0; i < l; i++) {

This is not something I can remember seeing as a best practice in languages that are more focused on performance than JavaScript. In fact, the bad code example seems to be preferred.

Is this best practice something particular for JavaScript, or is is true for other languages?

Bad Practice

for (i = 0; i < arr.length; i++) {

For every iteration in the loop, the condition is evaluated. If it is being arr.length then every time you are trying to access length property from arr . However, on the other hand, if you are storing it in a variable you are avoiding that operation.

Of all the ways to loop in javascript, the for-in loop is the safest in my opinion.

It can loop through the properties in an object.

let user = {first:"billy", last:"bob"};
for(let i in user){
    console.log(i);
    console.log(user[i]);
}

It doesn't throw an error if the variable is null

let empty = null;
for (let i in empty){
}

It works with arrays

let arr = [3,2,1];
for (let i in arr){
    console.log(i);
    console.log(arr[i]);
}   

.map .filter .reduce .forEach throw errors with anything but arrays(null, objects etc)

So if you want one loop that works for everything, for-in is you what you want.

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