11

I'm using TSLint in a TypeScript project and it's complaining about the variable i in the following code:

    for (let i = 0; i < body.children.length; i++)
    {
        body.children[i].classList.remove('active');
    }

The message is 'Shadowed variable: 'i' (no-shadowed-variable)'

Is there anything wrong with this loop and what would be the correct way of doing a for loop in TS?

rbasniak
  • 4,484
  • 11
  • 51
  • 100
  • 1
    Could you add all code of this method? Do you have another i in you code? One of the solutions you can try to rename i and all should work fine. – Vladislav Kievski Sep 24 '17 at 18:45

1 Answers1

23

Shadowing means declaring an identifier that has already been declared in an outer scope. Since this is a linter error, it's not incorrect per se, but it might lead to confusion, as well as make the outer i unavailable inside the loop (where it is being shadowed by the loop variable.)

You can rename either of the i variables, but if you add the rule "prefer-for-of": true to your tslint.json, TSLint will suggest an elegant solution in this case:

for (const child of body.children) {
    child.classList.remove('active');
}

(provided child hasn't been declared already :-)

Oblosys
  • 14,468
  • 3
  • 30
  • 38