Monday, 4 April 2016

Returning a function from another function - closures in javascript

closures are used to persist functions in javascript. It helps us to persist functions and access their context. We can have access to the variables inside the functions even when we are outside the function as the function is not garbage-collected due to persistence.
//closures
var salaryUpdater = function(salary){
 var currentSalary = salary;
  var generator = function(){
   currentSalary *= 2;
    return currentSalary;
  };
  return generator;
};
var updateFtn = salaryUpdater(50000);
console.log(updateFtn());//100000
//*************************************************************
/* 
To prove that the function salaryUpdater and its context is persistent
we will call it twice and will show that the increment made in the
first call remains and the second call increments the salary further. 
*/
var salaryUpdater = function(salary){
 var currentSalary = salary;
  var generator = function(){
   currentSalary += 5000;
    return currentSalary;
  };
  return generator;
};

var updateFtn = salaryUpdater(30000);
updateFtn();
console.log(updateFtn());//40000
//*************************************************************

1 comment:

  1. Lucky Club Casino site | Live score, live scores, jackpots and free
    Lucky Club luckyclub Casino is an online casino where you can enjoy all of your favourite online slots, bingo and live dealer games at one of the best

    ReplyDelete