flatbubba
11/26/2017 - 11:11 PM

Closures

function doSomeMath(){
  var a = 5;
  var b = 4;
  
  function multiply(){ // This is a CLOSURE:
    var result = a*b;  // a funciton inside of a function that 
    return result;     // relies on variables in the outside function to work.
  }
  
  return multiply; //don't run the funtion, just return the function
}

var theResult = doSomeMath();

console.log("The result is: ", theResult()); //This looks weird because what this is essentially saying is: run the function (the multiply() function) that we returned when we said "return multiply". This still returns 20 because we are now calling the function ( theResult() ) and the browser sees that we still need the info from the parent function: doSomeMath(). Normally variables inside the function would be dumped after the function is done running but a CLOSURE keeps that info stored for use, as in this case.