Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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.
<!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>