JavaScript Execution Contexts

Execution contexts are a fundamental part of understanding how JavaScript works yet there is a lot of confusion surrounding the concept.

The execution context is simply the environment in which a particular line of code executes.

The execution context stack is a collection of execution contexts.   The global context is created first when the browser loads the code and is always at the bottom.    Each function invocation creates a new execution context which is pushed onto the stack.  Once the current function finishes executing, it will be popped off the stack and control will return to the one immediately below it.   The current/active execution context is always at the top.

The code below illustrates 3 separate execution contexts at work.  Notice that the variable myVar is declared in three separate locations and stores a different value each time.

'use strict';

function b() 
    let myVar;  //undefined
    console.log('This is function b ' + myVar)

function a() 
    let myVar = 2; //only defined in this function context
    console.log('This is function a ' + myVar);

let myVar = 1; //global context
console.log('Global context ' + myVar);