I've been trying to wrap my head around scope, specially closures. I know that there are many posts about the topic, and I've been reading a lot. But most places refer to the topic as advanced, and use terminology that is relatively difficult to grasp. I would like to be absolutely sure that I've got the basics right, so that I don't go venture into the more intricate topics with a wrong idea of how functions really work.
So... I picked a basic function, and would really like for someone to tell me if what I think its happening under the hood is what is actually happening.
This is the code:
function sum(a) {
return function(b) {
return a+b
}
}
console.log( sum(1)(sum(2)))
(I know that it's not actually do the sum, I was tweaked with it, to try to understand what was going on in each step.)
So, my main doubt was why A was 1, and not 2. I reached the conclusion that the closure is created, as soon as function(b)
is created to take sum(2)
as an argument, right after being returned by sum(1)
. Therefore, by the definition of closure, I'm assuming that at the time the function is created it also saves the lexical environment (in which a = 1
). Is this right?
I've made a diagram of the steps.
In the next function you will see how the
greet
will use a variablesalute
declared inside thegreeting
function even when this is no longer being called, this is called a Closure.You can learn a lot more about closures in the Kyle Simpson's book series You Don't Know JS but for this particular topic check You Don't Know JS: Scope & Closures. He uses a simple and up to the point language to explain difficult concepts like this one.