The value of x is not determined until runtime. Thus, console.log(x) has no idea what will be printed out. Also, x is neither a globally variable nor is defined within the log function. But log has access to it.

Note: this example above does not work in Javascript because JS does not support dynamic scoping.

So now we understand what the fancy term lexical scope means, let's take a look at the definition of first-class function

Closure

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

functionouter(){varx=5;// the so called 'free' variable that can be accessed by inner()
functioninner(){console.log(x);}returninner;}vartest=outer();// outer() actually returns inner(), thus exposing inner() to the outside world
test();// output 5

Highlights of this example:

inner() has access to variable x, which is defined outside of it

var test = outer() is equivalent of var test = inner() but test has no access to x

The value of x is stored in memory so that any subsequent call of test() will print 5