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?

1
  • You can declare that function outside the for scope and achieve the same result while being more clear Commented Apr 28, 2019 at 20:12

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I cannot understand clearly... in my example shoul I change for (j = 0 to for (let j = 0?
.... jshint gives a warning with array1, how can the let j change something? actually, adding the let, jshint keeps giving me the same warning
But now you can ignore it without feeling bad :)
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();
    }
}

Comments

-1

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

1 Comment

Why not give the code instead of just describing?!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.