Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "Shadow Identifier Declaration" in JavaScript?

Tags:

javascript

While reading a JavaScript article I came across this term "Shadow Identifier Declaration". Can someone explain what this is? If possible please provide a simple example too.

snapshot from the article

like image 611
Aaditya Sharma Avatar asked Feb 11 '17 09:02

Aaditya Sharma


1 Answers

It's when you declare an identifier in a scope that hides one that exists in the containing scope:

var foo; // The outer one
function example() {
    var foo; // The inner one -- this "shadows" the outer one, making the
             // outer one inaccessible within this function
    // ...
}

There are several ways you might shadow something:

  1. With a variable declaration (var, let, const), as above

  2. With a parameter declaration:

    var foo; // The outer one
    function example(foo) { // This parameter shadows the outer `foo`
        // ...
    }
    
  3. With a function declaration:

    var foo; // The outer one
    function example() {
        function foo() { // This shadows the outer `foo`
        }
        // ...
    }
    

...and several others. Anything that declares an identifier within a scope that hides (shadows) one in the containing scope, that's a shadowing declaration/definition.

like image 71
T.J. Crowder Avatar answered Oct 14 '22 19:10

T.J. Crowder