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 > Conceptual Overview of JavaScript Scope

Conceptual Overview of JavaScript Scope

In JavaScript, scope is the context in which code is executed, and there are three types of scope: global scope, local scope (sometimes referred to as “function scope”), and eval scope.

Code defined using var inside of a function is locally scoped, and is only “visible” to other expressions in that function, which includes code inside any nested/child functions. Variables defined in the global scope can be accessed from anywhere because it is the highest level/last stop in the scope chain.

Examine the code below and make sure you understand that each declaration of foo is unique because of scope.

Live Code

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

var foo = 0; // global scope
console.log(foo); // logs 0

var myFunction = function() {

   var foo = 1; // local scope

   console.log(foo); // logs 1

   var myNestedFunction = function() {

       var foo = 2; // local scope

       console.log(foo); // logs 2
   }();
}();

eval('var foo = 3; console.log(foo);'); // eval() scope

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

  

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