How and Why to Avoid ‘for’ Loops

Ciprian on Wednesday, January 17, 2018 in JavaScript Arrays & Objects

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Never again use for() for looping. Using for() can be dangerous, especially if you use a library which adds attributes to native objects. Change this loop:

for (i in my_array_or_object) {
    if (my_checking_function(my_array_or_object[i])) {
        break;
    }
}

or

for (i = 0; i < my_array.length; ++i) {
    if (my_checking_function(my_array[i])) {
        break;
    }
}

to

[].forEach.call(my_array_or_object, item => {

    // Do something with item
});

If the circumstances force you to use a for() loop, do it this way:

for (i in my_object) {
    if (!my_object.hasOwnProperty(i)) {
        continue;
    }

    if (my_checking_function(my_object[i])) {
        break;
    }
}

Related posts

Leave a Reply

You have to agree to the comment policy.