1

The javascript code:

for (j = 0; j < array.length; j ++) {
    if (
        array[j].some(
            function(word) {
                return word.indexOf(array1[i]) > -1;
            }
        )
    ) {
        makeSomething();
    }
}

produces a Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (array1) warning in jshint.com.

Actually it works.

Is it really problematic?

How should it be written?

Paolo Benvenuto
  • 385
  • 4
  • 15

3 Answers3

2

No this is not a problem. The warning is missing the reasoning:

If the callback would be called back asynchronously, then it would be confusing:

   for(i = 0; i < 10; i++) {
      setTimeout(function() {
        console.log(i); // guess what this logs
      });
  }

But you should really always declare variables and always use let or const for that:

  for (let j = 0; j < array.length; j ++) {

that will make the warning go away, and will also fix the example above (and it avoids a probably confusing implicit global).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You can declare that function outside the for scope and achieve the same result while avoiding the warning.

const functionName = function(word) {
    return word.indexOf(array1[i]) > -1;
}

for (let j = 0; j < array.length; j ++) {

    if (array[j].some(functionName)) {
        makeSomething();
    }
}
J. Nicastro
  • 254
  • 3
  • 11
-1

you need just to declare the function outside the for loop , then call it inside the loop as guest

madjed-hue
  • 16
  • 3