JavaScript Execution Context Overview

Jul 29, 2024

Notes on JavaScript Execution Context

Introduction to Execution Context

  • Definition: Everything in JavaScript happens inside an Execution Context.
  • Importance: Without the Execution Context, JavaScript wouldn’t function.
  • Key phrase: When running a JavaScript program, an execution context is created.

Phases of Execution Context Creation

  1. Creation Phase (Memory Creation Phase)

    • Allocates memory to all variables and functions.
    • Sets initial values for variables to undefined.
    • Stores the whole code of functions.

    Example:

    • Variable n (value: 2) → Memory allocated, initial value: undefined.
    • Function square → Memory allocated, function code stored.
    • Other variables (square2, square4) → Memory allocated, initial value: undefined.
  2. Code Execution Phase

    • Executes the code line by line.
    • Takes the previously allocated memory and updates values.
    • Example:
      • n=2undefined replaced with 2.
      • Invoking square(n) creates a new execution context.

Function Invocation and New Execution Context

  • When a function is invoked, a new execution context is created, with:
    • Memory Component
    • Code Component

Execution Context Creation for Function square

  1. Memory Creation Phase:
    • Memory allocated to parameters (num, ans), both initialized to undefined.
  2. Code Execution Phase:
    • num receives the value from n (which is 2).
    • Calculation performed: ans = num * num → Result stored in ans.
    • Return statement sends the result back to the point of invocation.
    Example: If n=2, then ans becomes 4 upon returning
    Invocation of square2 gets value 4.

Clean Up of Execution Context

  • Once function execution is complete, the execution context is deleted.
  • Memory reassigned during new invocations.
  • Each subsequent invocation creates a new context, repeating the two phases.

Call Stack in JavaScript

  • Definition: A stack structure that manages the execution context creation and deletion.
  • Functioning:
    • Global execution context at the bottom of the stack.
    • When a function is invoked, a new execution context is pushed onto the stack.
    • On completion, it is popped off the stack, returning control to the previous context.

Example of Call Stack Usage

  • Creating execution contexts: E1 for square2 and E2 for square4.
  • Each execution context pops off the stack upon completion.
  • Important Aspect: Call stack maintains the order of execution.

Terminology

  • Call stack also known as:
    • Execution context stack
    • Program stack
    • Control stack
    • Runtime stack
    • Machine stack

Conclusion

  • The process of execution context creation, function invocation, and call stack management is fundamental to how the JavaScript engine operates.
  • Understanding these concepts is essential for mastering JavaScript.