//Lets start with a basic Javascript snippet function generateCash() { var denomination = []; for (var i = 10; i < 40; i += 10) { denomination.push(i); } return denomination; }
This is the main function statement in Javascript, which returns an array from [10,20,30]
//--Lets go a step further function generateCash() { var denomination = []; for (var i = 10; i < 40; i += 10) { denomination.push(console.log(i)); } return denomination; }
This will print 10, 20, 30 sequentially as the loop repeats, but will return an array from [undefined, undefined, undefined], the main reason is that we do not press the actual value of i, we just print it, so the javascript mechanism at each iteration will set it to undefined.
//--Lets dive into closures function generateCash() { var denomination = []; for (var i = 10; i < 40; i += 10) { denomination.push(function() { console.log(i) }); } return denomination; } var dn = generateCash(); console.log(dn[0]()); console.log(dn[1]()); console.log(dn[2]());
It's a little complicated what you expect from the exit, will it be [10,20,30]? There are no answers. Let's see how this happens. First, a global execution context is created, when we create dn, we also have the generatecash () function. Now we see that as the for loop iterates through it, it creates three anonymous function objects, it may be tempting to think that console.log inside the push function also works, but this is actually not the case. We launched the call generateCash (), so the push function simply creates three anonymous function objects, this does not call the function. At the end of the iteration, the current local context is set from the execution stack and leaves the state i: 40 and arr: [functionobj0 (), functionob1 (), functionobj2 ()]. A.
So, when we start to execute the last three statements, all of them output 40, since it cannot get the value i from the current area, it rises to the chain of areas and discovers that the value i was the set value 40. The reason that all of of them will work, equal to 40, since each component of dn is in the same execution context, and they all can not find the value i in their current scope, will increase the chain of areas and find that I am set to 40 and display it accordingly