Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

7. Scope and Closures > The Scope Chain Lookup Returns the First Found Value

The Scope Chain Lookup Returns the First Found Value

In the code below, a variable called x exists in the same scope in which it is examined with console.log. This “local” value of x is used, and one might say that it shadows, or masks, the identically named x variables found further up in the scope chain.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var x = false;
var foo = function() {
   var x = false;
   bar = function() {
       var x = true;
       console.log(x); // local x is first in the scope so it shadows the rest
   }();
}

foo(); // logs true

</script></body></html>

Remember that the scope lookup ends when the variable is found in the nearest available link of the chain, even if the same variable name is used further up the chain.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint