Search code examples
javascriptfunctionscopeexecutionchain

Scope chain in Javascript and calling nested function within the global scope


Here is the example I want to be enlighten on (Something that doesn't actually works).

 var myVar = 2;

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

This will output in the console: Uncaught ReferenceError: b is not defined.

As you can see I have a function named a with a nested function called b.

At first I thought I could invoke b outside a and get it working normally. I thought that would work because at first I call the a function.

By doing that I had in mind the fact that the a function would be put on the execution stack and during its creation phase the b function defined inside would be set in the memory.

As this is in memory I thought I could then execute this outside the function. Which obviously doesn't work.

So my conclusion is the b function is indeed set into memory during the creation phase of the a function but once the a function has finished to execute, once it's popped of the execution stack, the b function gets popped off the memory at the same time.

Thus calling it (I mean the b function) within the global scope is impossible.

Am I right on this ?


Solution

  • You are complicating things unnecessarily by speaking about execution stacks, creation phases and such.

    The explanation is very simple: you cannot call b because the spec says that b is out of scope at the site where you are trying to call it. That is all, end of story.

    Your example would actually work if converted to PHP, which makes me think that perhaps this is where you got the idea from. But JS and PHP are different languages and the (IMO ridiculous) manner that PHP treats nested functions does not transfer over.