3

I am trying to detect nested loop with the same index which looks like this:

for(let i = 0; i < 10; i++) {
    for(let i = 0; i < 10; i++) {
    }
}

I have searched Eslint rules but haven't found any solution so far. Is there a way to detect this bad code smell? Thanks a lot.

7
  • 1
    I can't help trying to be humorous and pointing out that in that particular case, it won't matter, since the inner loop body will never run. ;-) (i = 0; i < 0...) ;-) Commented Mar 17, 2021 at 11:12
  • Why is a nested loop considered a "bad code smell"? Or do you mean that the loops share variables? Commented Mar 17, 2021 at 11:12
  • @evolutionxbox - Not nested loops per se, nested loops with the same index variable. The inner one will shadow the outer one. I could see the argument that this is asking for trouble. :-) Commented Mar 17, 2021 at 11:13
  • 3
    There is a lint rule for this eslint.org/docs/rules/no-shadow, I assume it would detect this case Commented Mar 17, 2021 at 11:15
  • 1
    @T.J.Crowder it was your use of shadow that reminded me of its existence Commented Mar 17, 2021 at 11:20

2 Answers 2

6

ESLint has the no-shadow rule that would flag that up, as well as other places where you've shadowed an outer scope variable with an inner scope one. For example:

{
    "no-shadow": ["error", { "builtinGlobals": false, "hoist": "functions", "allow": [] }]
}

Demo on the ESLint site:

for(let i = 0; i < 10; i++) {
    for(let i = 0; i < 10; i++) {
//          ^−−−−− 'i' is already declared in the upper scope on line 1 column 9.
        console.log(i);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

-1

You can't do it, since it's pure logic

Comments

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.