Recursive closure in JavaScript

437 views Asked by At

enter image description here

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

2

There are 2 answers

15
Manoj Lodhi On BEST ANSWER

A closureis a special kind of object that combines two things: a function, and the environment in which that function was created.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

2
Peter Paul Kiefer On

The developer tools displays the variable a which is a variable that points to a anonymous function/closure.

In javascript a function is defined in a scope and also it can define a scope by its body block. A scope "knows" all variables inside the defining block and all variables that are defined outside of the function but in the hierachy of scopes the scope is defined in.

The tools show you the scope of the returned function (a in this case). The function first is defined in the scope of the function a.

The variable first is also known in the scope of the anonymous function you assigned to the variable first.

And that what what you get on your screen: first is a variable containing a function. In the scope of this function a variable first is known that points to a function. In the scope of this function ...

You see?