1

I have been fiddling around with some piece of Javascript and I find console logs 1 for below code, However I was expecting 2, as it is 'a' which created b.

function b(){      
   c();
    function c(){            
        d();
        function d(){
             console.log(myVar);
        }
    }
}
function a(){
    var myVar=2;

    b();
}
var myVar=1;

a();

But again I see b sits in lexical environment of window so it is getting the value from there. So how does scope chain work?Does it take value from caller/ creator or lexical scope?

Noob
  • 69
  • 6
  • The scope chain will be created during the time when JS engine interprets the code. – Rajaprabhu Aravindasamy Jul 23 '16 at 14:43
  • 1
    `a` did not "create" `b`. It just called it. The scope is determined by where the function is defined, not where it's called. – JJJ Jul 23 '16 at 14:46
  • 1
    I can see how this particular example might be confusing with regards to the value that `myVar` takes on, but technically you actually have **2** `myVar`s. the `myVar` in function a is actually a redeclaration, assigning an inner `myVar` to 2 which does not affect the outer one. Had function a set `myVar` like `myVar = 2`, then the global one would have been overridden and the log printed "2". https://jsbin.com/jojaguwoku/edit?js,console – Perry Mitchell Jul 23 '16 at 14:50
  • @PerryMitchell: Yeah it was redclaration which was confusing ! Now I got it ! Thanks for your insight and jsbin ! – Noob Jul 23 '16 at 15:01

0 Answers0