Laurence L Laurence L - 11 months ago 46
jQuery Question

Moving function outside a loop

I have read the solution on the following page but still don't understand how to apply it to my loop and function. How do I move the following function outside the loop?

How to move functions outside a loop

var i;
var chap = '.nav__chapter-';
for (i = 0; i < 7; i++) {
var precedingZero = (i<10) ? '0' : '';
(function(i) {
$( chap + precedingZero + i ).addClass('toggleAria');
})(i);
}


I have a few like this so once I understand it I can apply to all. Sorry for being so dense.

Answer Source

You don't need your IIFE (immediately invoked function expression) in the loop at all. You can change to just this:

var chap = '.nav__chapter-', precedingZero;
for (var i = 0; i < 7; i++) {
    precedingZero = (i < 10) ? '0' : '';
    $(chap + precedingZero + i).addClass('toggleAria');
}    

An IIFE might be used inside a loop if you have async operations and you need to "save" a loop value for later use in an async callback. But, that is not happening at all here so the IIFE is simply not needed.