Why is this an issue?

Variable shadowing happens when a variable declared in a specific scope has the same name as a variable in an outer scope.

This can lead to three main problems:

To avoid these problems, rename the shadowing, shadowed, or both variables to accurately represent their purpose with unique and meaningful names.

Note that functions in JavaScript are first-class citizens. This means that they possess the same attributes as variables, including the ability to shadow other variables and, conversely, be shadowed by them.

Noncompliant code example

The example below shows the typical situations in which shadowing can occur.

function outer(items) {
  var counter = 0;

  function inner(items) { // Noncompliant: the parameter "items" is shadowed.
    var counter = counter + 1; // Noncompliant: the outer "counter" is shadowed.
  }

  inner(items);

  return counter; // returns 0
}

function search(items, match) { // Noncompliant: the function "match" (below) is shadowed.
  // ...
}

function match(value, key) {
  // ...
}

Resources

Related rules