0

jshint doesn't like the code below, and reports:

Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. ($)

   const suffix = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
   for(let i=0; i<suffix.length; i++) {
      (function(i) {
         $('#foo'+i).click(function() {
            $('#bar'+i).modal({show:true});
            return false;
         });
      }(suffix[i]));
   }

The code creates click handlers for fooA through fooH, and pops up modals barA through barH on the relevant click.

Granted, it is confusing, but is there a better way to do this, or should I just turn the warning off?

QF0
  • 329
  • 2
  • 14
  • 1
    An IIFE inside a `for` which already uses a `let` - what's the point of that? Also, numbered (well, in this case, "lettered") IDs (or classes) are usually an antipattern. Use a selector that matches all the things you want - a class or even a custom attribute. Then make use a [delegated event handler](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) so you don't even have to loop and attach a handler to each. – VLAZ Mar 01 '23 at 15:32

0 Answers0