O'Reilly logo

JavaScript Enlightenment by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Scope and Closures

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>

Please notice that each foo variable contains a different value because each one is defined in a specifically delineated scope.

Notes

  • An unlimited number of function and eval scopes can be created, while only one global scope is used by a JavaScript environment.

  • The global scope is the last stop in the scope chain.

  • Functions that contain functions create stacked execution scopes. These stacks which are chained together are often referred to as the scope ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required