Skip to main content

Posts

Showing posts with the label closure

Closures in Javascript

function add ( num ) { var counter = 0 ; return function ( num ) { counter += num return counter } } const addValue1 = add (); console . log ( addValue1 ( 2 )) console . log ( addValue1 ( 4 )) console . log ( addValue1 ( 1 )) console . log ( addValue1 ( 9 )) console . log ( addValue1 ( 1 )) const addValue2 = add (); console . log ( addValue2 ( 10 )) console . log ( addValue2 ( 20 ))

A closure is a persistent local variable scope

Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere. outer = function () { var a = 1 ; var inner = function () { console . log ( a ); } return inner ; // this returns a function } var fnc = outer (); // execute outer to get inner fnc (); As you might be able to guess, when I call  fnc()  it prints the value of  a , which is "1". =========================== function add (a) { return function (b) { return a + b; } } var add3 = add(3); add3(4); // returns 7 ======================== var  add = ( function  () {    var  counter =  0 ;    return   function  () {counter +=  1 ;  return  counter} })(); add(); add(); add(); // the coun...