javascript interactive

JavaScript Interactive — a console crash course


3.4 Scopes & Closures

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
  • Variable Scope – Names in JavaScript are bound to either the global namespace or a parent function. Each function thus declares it's own namespace.
  • Parent Scope – The variable scope for a function also references the parent scope where the function was defined. This forms a chain of scopes, leading back to the global scope.
  • Closure – The function closure is the source code and the scopes reachable from it. Since name lookups traverse the scope chain, all parent scopes are part of the closure.
>>>
var a = 1;


  
>>>
function test() {
    var a = 2;
    return a;
}


  
>>>
test()
2
As expected, the local variable in the function shadows the global variable value.
>>>
a
1
The global value remains unmodified and is the only one accessible from the global scope (where this console runs).
>>>
function inc() {
    return b++;
}

  
A function can reference names in the parent scope. Even if those names do not yet exist.
>>>
inc()

  
The error happens in run-time, if the name cannot be found.
>>>
var b = 13;

  
>>>
inc()
13
By retroactively creating the missing variable, we can make the function work correctly. This shows that the name is looked up at run-time on each call. This is naturally very useful, but omitted var declarations inside functions is also one of the most common causes for bugs.
>>>

Index 1 2 3 4 5 6 7 8 9