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 (Lexical Scoping)

The Scope Chain (Lexical Scoping)

There is a lookup chain that is followed when JavaScript looks for the value associated with a variable. This chain is based on the hierarchy of scope. In the code below, I am logging the value of sayHiText from the func2 function scope.

Live Code

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

var sayHiText = 'howdy';

var func1 = function() {
   var func2 = function() {
       console.log(sayHiText); /* func2 scope, but it finds sayHiText in 
                               global scope */
   }();
}();

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

How is the value of sayHiText found when it is not contained inside of the scope of the func2 function? JavaScript first looks in the func2 function for a variable named sayHiText. Not finding func2 there, it looks up to func2’s parent function, func1. The sayHiText variable is not found in the func1 scope, either, so JavaScript then continues up to the global scope where sayHiText is found, at which point the value of sayHiText is delivered. If sayHiText had not been defined in the global scope, undefined would have been returned by JavaScript.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

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

  

Start a Free 10-Day Trial


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