0

I am new to closure concept of javascript. As i understood, By runtime call object stores reference to arguments, local variables and named parameters of function. With that, i tried to solve below snippet.

    function a(){
        var o=10;
         function b(){
             alert(o);
             var o=20;
             alert(o);    
         }
        alert(o);
        b();
    }
    a();

I expected the answer to be alert of 10, 20, 20, but it comes as 10, undefined, 20. Because b's call object stores reference to all local variables, first alert(o) in b should give 20, but why undefined is coming? Even if in b(), var o is defined at later point of time after alert(o), for that scenario shouldn't it access o from parent scope? Can somebody through some light on it!.

Rakesh_Kumar
  • 1,442
  • 1
  • 14
  • 30

1 Answers1

1

Because b's call object stores reference to all local variables

Yes. Local variables first, then parent scope variables.

first alert(o) in b should give 20, but why undefined is coming?

You've got two o variables here: One in the a scope, and one in the b scope. Due to hoisting, the variable declaration of var o=20 holds for the entire b scope, introducing an o variable (which is initially undefined) into the scope when b() is called.

Maybe this makes more sense:

function a(){
    var o; // hoisted
    function b(){ // hoisted
        var o; // hoisted
        alert(o);
        o=20;
        alert(o);    
    }
    o=10;
    alert(o);
    b();
}
a();

Btw, you've not yet experienced a closure, whose distinguishing feature is that the parent scopes are persistet with the child function objects, even after the parent function has returned.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • May you please elaborate on "hoisting"? One more thing needs to be clarified is, this call object creation for functions are done at runtime or when the functions are define,i.e, lexically? – Rakesh_Kumar Sep 09 '14 at 18:27
  • The call object creation happens at runtime, when the function is called. I think for further questions you should have a look at the duplicate question that @apsillers found (and I had forgotten about, shame about me). – Bergi Sep 09 '14 at 18:29