Closures — The way encapsulation and Module patterns work in JavaScript

  1. Access/Remember Lexical scope
  2. Function executing outside its lexical scope
function doSomething(){
var a = 5;

function printIt(){
console.log(a);
}
return printIt;}var closureFn = doSomething();closureFn();
Scope: [ (doSomething) => { a : 5, printIt: pointer to the fn's location in the heap}]->[(globalScope) => {}]
function grandParentDoSomething(){  
var a =5
function parentDoSomething(){
var b= 10;
function doSomething(){
var c = 15;
function printIt() {
console.log("HEY")
}
return printIt;
}
doSomething()
}
parentDoSomething();
}
var chainedClosure = grandParentDoSomething();/* Here all the variables a, b, c are preserved*/
  1. Module Pattern in JS ( modules are created using this)
  2. Security Purpose ( Just like protected keywords in Java)
function wallet(){

var currentAmount = 1000;
function deposit(amt){
currentAmount += amt;
}

function withdrawal(amt){
currentAmount -= amt;
}
function currentBalance(){ return currentAmount;
}
return {deposit, withdrawal, currentBalance };};var walletA = wallet();
console.log(walletA.currentBalance()); // 1000
walletA.deposit(50);
walletA.withdrawal(200);
console.log(walletA.currentBalance()); // 850
function() print{    for(var i=1;i<=6;i++){
setTimeout( function(){ console.log(i); }, 1000 );
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store