You-dont-know-js: Scope and Closures

Created on 13 Dec 2017  路  7Comments  路  Source: getify/You-Dont-Know-JS

Hey @getify
In the Scope and Closure book, you said that in the compilation phase, all variables are declared and initialized if they have been declared using var.

Consider the code below

function foo(i) {
    setTimeout(function callback() {
      console.log(i);
    }, 1000);
  }

for(var i =0; i < 5; i++) {  
  foo(i);
}

My question is when do those buckets are created. Since if the compilation phase only creates the buckets then all calls for a function should share the same bucket and the below code should print:

5
5
5
5

But this is not the case. It rather prints:

1
2
3
4

Which means the buckets are created at runtime and a different bucket(aka scope) is created for different calls for the same function.
Is this right?

Most helpful comment

no... it means one time compilation, always, no matter where the function is. compilation sets up what kind of environment each scope would need, and then runtime is when that blueprint is instantiated.

All 7 comments

@rajatvijay, it creates a new scope per iteration,

for (let i=1; i<=5; i++) {
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}

let keyword also create new scope per iteration, because the variable will be declared not just once for the loop, but each iteration.
reference link https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md (Block Scoping Revisited)

The function foo created a new scope per iterations?

So whenever a new scope is created the same 3 phases are run again?
Since we have a new scope manager, the compiler has to run again and declare and initialize variables in the scope?

Check out this, here you will know how each time new scope is create in js

The compiler parses the code and sets up a plan for a lexical environment to represent each scope (aka function... or block), but JS doesn't technically create that lexical environment (scope) until it's time for that scope to execute during runtime.

So, a single function represents not just a single scope itself, but a blueprint for a scope that will be created whenever that function is called. If the function is called once, then only one lexical environment (scope) is created. If it's executed 10 times, 10 "instances" of that scope are created, each as separate from the others.

Thanks, @getify, That means 10 times compilation phase and runtime phase executed when we call a function inside a loop?

no... it means one time compilation, always, no matter where the function is. compilation sets up what kind of environment each scope would need, and then runtime is when that blueprint is instantiated.

Thanks @getify

I think this makes a good point to be added to the book. (Maybe this edition or the second one)

Was this page helpful?
0 / 5 - 0 ratings