How to detect nested loop with same index in JavaScript/TypeScript

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.

Answer

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);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *