Disallow Shadowing (no-shadow)

Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. For example:

var a = 3;
function b() {
    var a = 10;
}

In this case, the variable a inside of b() is shadowing the variable a in the global scope. This can cause confusion while reading the code and it’s impossible to access the global variable.

Rule Details

This rule aims to eliminate shadowed variable declarations.

The following patterns are considered warnings:

var a = 3;
function b() {
    var a = 10;
}
var a = 3;
var b = function () {
    var a = 10;
}
var a = 3;
function b(a) {
    a = 10;
}
b(a);
var a = 3;

if (true) {
    let a = 5;
}

Options

This rule takes one option, an object, with properties "builtinGlobals", "hoist".

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

builtinGlobals

false by default. If this is true, this rule checks with built-in global variables such as Object, Array, Number, …

When {"builtinGlobals": true}, the following patterns are considered warnings:

function foo() {
    var Object = 0; // shadowed the built-in globals.
}

hoist

The option has three settings:

Thought with the following codes:

if (true) {
    let a = 3;
    let b = 6;
}

let a = 5;
function b() {}

Further Reading

Version

This rule was introduced in ESLint 0.0.9.

Resources