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 ...

Get JavaScript Enlightenment now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.