A closure is a function defined within another scope that has access to all the variables within the outer scope

The more I read about this the more complicated it became… I knew what closure was and used it, but found it hard to follow from the descriptions,  it’s best to look at an example.

function shane() {
  var name = 'Shane';
  function showName() {
     console.log(name);
  } 
  showName();
}

shane();

The closure in the above example is showName. Creating a function inside a function inside a function means a closure is created. This nested function has access to variables declared in the outer scope.

function shane() {
  var name = 'Shane';
  function showName() {
     console.log(name);
  } 
  return showName();
}

var someone = shane();

The above code works in the exact same way. In the instance the variable someone has become the closure.

In these examples the showName function is able to access the name variable in the outer scope as they’re in the lexical scope. Lexical scoping defines how variable names are resolved in nested functions, these are the words of Pierre Spring and you can read his post on this here.

Here’s an interesting example which is a modification from an example found on Mozilla

function addNumber(num) {
  return function(otherNum) {
     return num + otherNum;
  }
}

var addTwo = addNumber(2);
var addTen = addNumber(10);

// 3 + 2 = 5
console.log(addTwo(3));

// 10 + 1 = 11
console.log(addTen(1));

The closures are created in the addTwo and addTen variables. They both share the same function, but they pass in different numbers when the function is executed, meaning that they possess different addition numbers.

The best post I have found on closures is this which offers some more complex examples. It is used in this extensive stackoverflow question. There’s also a great analogy here.

Worthy of Note

Worthy of Note is a site aimed at Web Designers & Developers. It offers a wide range of resources to help assist anyone in the web industry.

View