Java Script


#1

What is a “closure” in JavaScript? Provide an example.


#2

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

var add = (function () {
    // this is the "self invoking" function that is only run once.
    // it sets the "counter" variable to 0 and returns a function
    // this return function gets assigned to the "add" variable, which makes "add" a function that can be called with add();
    var counter = 0;
    function private_function(){ alert('foo'); }
    return function () {  
      // this is the "closure". it has access to the private variables defined in the "self invoking" function above.
      return counter += 1;
    }
})();

add();
add();
add();

// the counter is now 3

private_function(); // doesn't work because we don't have access to the private scope within the "add" variable, only the closure can access this private function. 


#3

THANK YOU :grinning: