I recently read that the jQuery ‘each’ construct is more performance intensive than running a simple ‘for’ loop, which is borne out by testing. The ‘FOR’ loop being a native Javascript function is undoubtedly faster, however the scope is all the same, so in some cases the .each() method would be preferable, as each iteration is its own scope.

I decided to convert some of the my forEach() and each() functions to for loops to improve my scripts performance and immediately ran into a problem: when iterating through a list of elements whilst I could identify the element we were on, I really struggled to access that element.
Here’s an example of the ‘.each()‘ method

$('section h4').each(function(){
    var string = $(this).html(); 
    n = string.indexOf(" ") + 1;
    if(n !== 0) {
       string = string.substr(0,n) + '<span>' + string.substr(n) + '</span>';

And here’s the ‘for’ looped version:

let elements = $('section h4')
for(i=0; i > elements.length; i++) {
    let string = elements.eq(i).html()
    let n = string.indexOf(" ") + 1
    if(n !== 0) {
       string = string.substr(0,n) + '<span>' + string.substr(n) + '</span>'

There we go using the ‘.eq()‘ function we have sped up the process many times over.

Leave a Reply

Privacy & more..

Cookie Consent Policy