Last active
April 25, 2017 08:50
-
-
Save shahbazsyed/05cf58c59c6208413162f1c8ff5484ee to your computer and use it in GitHub Desktop.
Closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var addTo = function(passed){ | |
var inner=2; | |
return passed+inner; | |
}; | |
console.log(addTo(3)); // 5 | |
// Constant arguments can also be declared outside the function, and are accessible inside | |
var passedArg=3; | |
var addToNoArgs = function(){ | |
var innerVal=2; | |
return innerVal+passedArg; | |
} | |
console.log(addToNoArgs()); // We get the same answer 5 | |
/* | |
This is possible due to lexical scoping used by Js. This concept of functions being able to accesss/ store values from outer arguments | |
is called closure. Although it can get more complex, this example serves as a basic understanding | |
*/ | |
console.dir(addToNoArgs); | |
// Lets take a more complex example | |
var addNum = function(passedArg){ | |
var add= function(inner){ | |
return inner+passedArg; | |
}; | |
return add; | |
}; | |
var add3 = addNum(3); | |
var add4 = addNum(4); | |
console.log(add3(1)); // prints 4 | |
console.log(add4(1)); // prints 5 | |
// Hence by using closures, addNum preserves the value passed to it, and uses it in the computation of the add method! | |
// Currying is also a possible extension of Closures | |
var add= function(a){ | |
return function(b){ | |
return a+b; | |
} | |
}; | |
var addToFive = add(5); | |
console.log(addToFive(1)); // returns 6 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment