javascripttypescripteslinttslintsyntax-checking

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.


Solution

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