Before I start, let me give a huge shoutout to Jeff Kreeftmeijer for patiently being my partner/teacher/mentor for our JS book club; Also, this post is based on a book by Marijn Haverbeke called “Eloquent Javascript“.
So now, let me get into this Closure feature in JS. Basic question is of course, what is Closure?
As mentioned earlier, it is a feature. It lets a function to ‘closes over’ some local variables; This situation is also known as the “upwards Funarg problem” and many old programming languages forbit this.
Next, why do we use Closure?
Well for one reason, Closure frees you from worrying about “alive” variables. Secondly, once we get how Closure works, we can use function values creatively to fit our purpose(s).
* Please make sure you’re ready to type on your awesome console
Ok, now let’s dive into the code.
function formulaOne(base) {
return function(adder) {
return base + adder;
}
}
when we run formulaOne() on console, we will get this as a result
function(adder) {
return base + adder;
}
ok, now let’s make a new variable to make it simple
var awesomeFormula = formulaOne(2)
Next, let’s run awesomeFormula(3), then see what we get BAM!
=> 5
Confused? don’t be. Here is the secret:
awesomeFormula(3) == formulaOne(2)(3)
Ring a bell? So basically when we type awesomeFormula(3), here’s what’s happening:
function formulaOne(2) {
return function(3) {
// base = 2
// adder = 3
return 2 + 3;
}
}
Let’s make this a bit fun by returning another function inside function(adder) => not usually happen in real life but let’s do this just for fun:
function formulaOne(base) {
return function(adder) {
return function(multiply) {
return (base + adder) * multiply;
}
}
}
// Create a variable to simplify our function
var finalResult = awesomeFormula(3)
when we type, finalResult(5) == formulaOne(2)(3)(5) guess what we’ll get?
=> 25
function formulaOne(2) {
return function(3) {
return function(5) {
// base = 2
// adder = 3
// multiply = 5
return (2 + 3) * 5;
}
}
}
Not that complicated to understand right?
Bonus{Passing multiple arguments}:
function numberOne(basic, secondary){
return function(multiply) {
return (basic + secondary) * multiply;
}
}
numberOne(2, 3)(5)
=> 30
Explanation:
function numberOne(2, 3){
return function(5) {
return (2 + 3) * 5;
}
}
PS: Thank you so much for reading this post, any feedback will be more than welcome – please be nice tho, I am still in learning stage. Also if you have any suggestions, please let me know; I am really loving learning JavaScript these days