-1

After linting my code with JSHint, it came up with an advisement not to create new functions in a for loop like below:

for (var i = 0; i < AnArray.length; i++){
    // code that creates an element
    (function(_i) {
        element.addEventListener(
            "click",
            function() { DoSomething(_i); }
        );
    })(i);
}

Where DoSomething(arg) does something related to that Array entity. I've tried code like below, with no luck.

function RegisterClick (elem, i) {
    elem.addEventListener(
        "click",
        function() { DoSomething(_i) }
    )
}

for (var i = 0; i < AnArray.length; i++){
    // code that creates an element
    (RegisterClick (_elem, _i)) (element, i);
}
  1. Is this something I should worry about in the long run?
  2. Is there a way not to create new functions but get the benefit of closures?
Jason
  • 779
  • 1
  • 9
  • 30
  • *" it came up with an advisement not to create new functions in a for loop"* Right, but you are using IIFE to prevent exactly the issue JSHint warns about, so you'll be fine. *"I've tried code like below, with no luck."* What exactly does that mean? *"Is there a way not to create new functions but get the benefit of closures?"* A closure is a function. Without a function there is no closure. – Felix Kling Sep 08 '16 at 20:08

1 Answers1

2

I've tried code like below, with no luck.

You're over-thinking your code. You have way too many parenthesis. You just need to call the function. The return value is undefined, you don't need to call that. You also need to keep your variable names straight.

function register_click(elem, i) {
    elem.addEventListener(
        "click",
        function() { DoSomething(i) }
    );
}

var _elem = something_that_gets_an_element();

for (var i = 0; i < an_array.length; i++){
    register_click(_elem, an_array[i]);
}

Is this something I should worry about in the long run?

Creating the function separately makes for clearer code that is easier to read. It has fewer nested scopes, so it is easier to keep track of which variable is which.

Is there a way not to create new functions but get the benefit of closures?

You might be looking for let as described at the end of this answer.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335