getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

How and Why to Avoid ‘for’ Loops

Never again use for() for looping. Using for() can be dangerous, especially if you use a library which adds attributes to native objects. If you use jQuery, do loops with $.each(). 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

$.each(my_array_or_object, function(i, value) {
    if (my_checking_function(value)) {
        return false;
    }

    return true;
});

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

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Wednesday, January 17, 2018 in Blog, JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy