I am looping through a collection of DOM elements. Each iteration makes use of a helper() function several times like so:
$(".myclass").each(function() {
var arg;
helper();
// do stuff
function helper() {
// do helpful stuff with arg
}
});
Is it bad practice to include the helper() function inside the function() block as above? Should I use:
$(".myclass").each(function() {
var arg;
helper(arg);
// do stuff
});
function helper(arg) {
// do helpful stuff with arg
}
In the first example will every matched .myclass element have its own instance of the helper function in memory?
Edit: If anyone is looking for a good explanation of the answer – http://net.tutsplus.com/tutorials/javascript-ajax/stop-nesting-functions-but-not-all-of-them/
Yes, that will redeclare the function over and over again (every time the loop runs).
You can either put the function in a higher scope like in your second example, or if you want to keep the scope cleaner, you could do a closure around the function (though there are implications of this in terms of when the outer closure gets executed, how many times it gets executed and so on):
Note though that this still has the potential for helper to be defined more than once just not on every iteration.