Execution Context, Variable Environment and Closures.

Let us talk about the connection between the execution context, variable environments and the closure. Note, to better understand the closure and know how it works behind the scenes, we need to as well understand the execution context and the variable environment.

What is an Execution context?

Simply an environment where Javascript code runs.

What is a variable environment?

Simply an area where Javascript variables are declared.

Note: Each Execution context has a variable environment.

What is a closure in Javascript?

Closures make it possible for a function to access variables that exist in
the same execution context where it was created. That is a function has
access to the variable environment of the execution context where it was
created.

From our code below,

'f country' is a function in the global execution context and has in its variable environment 'cities' which is an array and 'f city' a function..

'f city' is a child function of '**f country'

let city;
// (f country)
const country = function () {
  const cities = ['Helsinki', 'Vantaa', 'Vaasa', 'Tampere', 'Espoo'];
  // (f city)
  city = function () {
    for (let i = 0; i < cities.length; i++) {
      console.log(cities[i]);
    }
  };
};

// 'f country' is called and executed as the parent function.
country();

// Javascript invokes 'f city' only after 'f country' has beeen completed.
city();

If 'f city' is a child function inside of 'f country' and considering that Javascript already called and completed the running of 'f country', How then does 'f city' come to life still?

closures closures closures

'f city' was created in the same execution context as 'cities' so, it has access to the variable 'cities'.

NB: closures are not created manually... They just happen when functions keep having access to variables that do not exist...