function buildList( list ) {
var i = 0;
var first = function () {
console.log( "in" )
console.log( i );
}
var Second = function () {
console.log( "out" )
first();
}
return Second;
}
var a = buildList( [1, 2, 3] )
console.dir( a );
a(); // Here closure is created which has function first ,Here first also has one closure of itself that means recursive closure
When i see my console in Chrome it has a closure which has function first which also has a closure of itself ie it has repetitive loop of its own function in closure, Does anyone knows whats happening here, I am very much confused, Why there is infinte closure loop
When function f is called recursively, the interpreter looks in the environment to find its closure. Since f is not a formal parameter (of itself), we look up the environment stack which is the environment stored in the closure.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
In a recursive function, there must be a termination condition that allows the function to exit without calling itself. This condition allows the recursion to stop - that is, without it the function would call itself over and over again, resulting in an error.
Callbacks are functions that are passed into another function as an argument. Closures are functions that are nested in other functions, and it's often used to avoid scope clash with other parts of a JavaScript program.
A closure
is a special kind of object that combines two things: a function, and the environment in which that function was created.
No need to be confused, the behavior is same as expected to this code. Here what happening is that when you do console.dir( a );
in your code it returns the Second
function, i think it is clear for you.
Now when you will expand this function it will show you in Closure
the parent function (environment function
) of Second
, which is buildList
. In you code it is doing the same thing.
Now next thing is to expand this function
buildList
, what it will show you is the child objects of it, Which are var i = 0;
and the function first
. Your console is showing as expected.
Now again when you open first()
it will show you in Closure
the parent function(environment function
) of first
, which is buildList
. (same it did in step 2).
Now it repeats the step 3 again and then step 4. and so onnn... May be you understand what is happening here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With