What is the "Shadow ID Declaration" in JavaScript?

While reading a JavaScript article, I came across this term "Shadow ID declaration." Can someone explain what this is? If possible, provide a simple example.

snapshot from the article

+6
source share
3 answers

This is when you declare an identifier in the scope that hides the one that exists in the content area:

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 to do something:

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

  • With parameter declaration:

     var foo; // The outer one function example(foo) { // This parameter shadows the outer `foo` // ... } 
  • With 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 the scope that hides (shadows) in the scope, that declares / defines shadow copy.

+5
source

Wikipedia definition ( https://en.wikipedia.org/wiki/Variable_shadowing ):

In computer programming, variable shading occurs when a variable is declared in a specific area (decision block, method, or inner class) and has the same name as a variable declared in the outer scope. In the level of identifiers (names, not variables), this is known as masking the name. This external variable is called the shaded internal variable, while the internal identifier is said to mask the external identifier. This can be confusing, as it may be unclear which variables subsequent use of the shadow variable name refer to depends on the rules for resolving language names.

Java example:

 public class Shadow { private int myIntVar = 0; public void shadowTheVar(){ // since it has the same name as above object instance field, it shadows above // field inside this method int myIntVar = 5; // If we simply refer to 'myIntVar' the one of this method is found // (shadowing a seond one with the same name) System.out.println(myIntVar); // If we want to refer to the shadowed myIntVar from this class we need to // refer to it like this: System.out.println(this.myIntVar); } public static void main(String[] args){ new Shadow().shadowTheVar(); } } 
+2
source

For your question, consider this code

 function foo(a) { var b = 2; // some code function bar() { // ... } // more code var c = 3; } 

In this snippet, when trying to execute from a global scope.

 bar(); // fails console.log( a, b, c ); // all 3 fail 

suppose in the function bar () {....} if you have other code, for example

 function foo(){ var b = 3; console.log(b); } 

then this means that foo linside bar obscures foo (a) in the global area

0
source

Source: https://habr.com/ru/post/1014895/


All Articles