Closures and IFFY

What is a closure?

A closure is a feature in Javascript where inner functions has access to outer function's variables (i.e. scope chain)

How does it work?

function outer(){
  var b = 5;
  
  function inner(){
    var a = 12;
    console.log(a + b);
  }
  return inner;
  
}
console.log(outer());

/*without closures, var b in the outer function will no longer exist 
after the outer function has been invoked*/

/*closures preserves the scope chain of the enclosing function when it is invoked, 
giving you access to the enclosing functions variables*/

Immediately Invoked Function Expressions (IFFY)

The primary reason to use an IIFE is to obtain data privacy. Because JavaScript's var scopes variables to their containing function, any variables declared within the IIFE cannot be accessed by the outside world.


Made with Slides.com