Confused by closures in JavaScript [duplicate]

Closures are something like the context of a function when it is defined. Whenever a function is defined, the context is stored, and even if the ‘normal’ life cycle of your function is over, if you keep a reference to an element defined whithin your function execution, it can still access to elements of the context (closure), which is actually the scope of your function in its definition. Sorry for my bad english, but probably this example will make you understand:

function test() {
  var a = "hello world";
  var checkValue = function() { alert(a); };
  checkValue();
  a = "hi again";
  return checkValue;
}

var pointerToCheckValue = test();  //it will print "hello world" and a closure will be created with the context where the checkValue function was defined.
pointerToCheckValue(); //it will execute the function checkValue with the context (closure) used when it was defined, so it still has access to the "a" variable

Hope it helps 🙂

Leave a Comment