Amandeep Singh
Nov 15, 2019 · 1 min read

JavaScript engine has to go through two step process: compilation/parsing and execution (interpretation). Normally people don’t think about the compilation process.

While compiling your code, JS engine creates a plan for scope chain, lexical environment, etc. Later, it hands over the plan to the interpreter for execution. Check out this nice AST explorer.

Engine doesn’t know if we are going to invoke our function in the future or not.

With basics aside, let’s look at your question:

In the first line, execution environment for foo has already been created (the compilation stage). This is irrespective of foo being invoked later or not. As we just learned that lexical environment captures the outer(parent) statically at creation stage, the anonymous inner function’s outer will point to foo’s env. record (which has binding for a).

This binding is what we call “closure capturing the variable in the parent scope”.

What happens to the lines following the first line can’t change the captured value. This is why we use the word “statically”.

    Amandeep Singh

    Written by

    Developer @ Thinkmill Sydney. Tech enthusiast and a pragmatic programmer. If coding is hard, you are not doing it right.