UP | HOME

Scoping in JavaScript

In JavaScript, there are only 3 types of scope: global scope, local scope (or function scope), and eval scope.

Eval is the obsoleted thing so we only care about global and local scope.

var a = 10; // global scope

function () {
  var a = 5; // local scope

  function () {
    var a = 1; // nested local scope
  }
}

Logic statements (if, case) or looping statements (for, while,…) does not create a scope, because JavaScript does not have block scope. So anything defined in these statements are belongs to its container scope.

function () {
  // both a and b are accessible here
  if (true) {
    var a = 10;
  }
  for (var b = 0; ...) {
  }
}

Scope chain (or, lexical scope) is a chain of scope lookup. If a variable is not found in a scope, it will go up to the parent scope to lookup. For example:

var a = 0;

function b() {
  var a = 5;
  function c() {
    return a;
  }
}

In the above example, `a` is not found in the scope of function `c()`, so it go up to the parent scope, function `b()` and found `a`. It's important to remember that, scope chain lookup returns the first found value, so in the above example, it won't return the `a=0` value in global scope.

Closure is a combination of a function and a lexical environment in which that function was created. For example:

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

add5 and add10 are closures, they contains the environment in the scope of makeAdder, and have access to all of the local variables at the time they created.

Date: 2019-01-15 Tue 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41