JS Tip of the Day: Variable Shadowing

Variable Shadowing
Level: Beginner

Scopes allow you to have independent containers for variables. Inner scopes can access variables from their outer scopes, but outer scopes cannot access variables from their inner scopes.

{ // outer scope
    let outer = 'outie';

    { // inner scope
        let inner = 'innie';
        console.log(outer); // outie (Ok)
    }

    console.log(inner); // ReferenceError (Not ok)
}

Variables in nested inner scopes can even have the same name as variables in their outer scopes. When this happens, the outer variable is said to be “shadowed” by the variable in the inner scope. Shadowed variables in outer scopes then become inaccessible from within the inner scope because only the inner scope version of the variable of that name can be accessed.

{ // outer scope
    let metal = 'gold';

    { // inner scope
        let metal = 'lead';
        console.log(metal); // lead
        // No way to access 'gold' metal here
    }
}

If you ever need to have an outer scope variable accessible in an inner scope, you’ll want to make sure not to have any other variables in that inner scope with the same name. There’s no super-like option that would allow you to access shadowed variables in outer scopes like there is with overridden members in object methods.

{ // outer scope
    let metal = 'gold';

    { // inner scope
        let innerMetal = 'lead'; // renamed
        console.log(innerMetal); // lead
        console.log(metal); // gold (yay!)
    }
}

More info: