🟑 MediumCore JSπŸ“– Theory Question

What is an Execution Context and what are its two phases?

πŸ’‘

Hint

Creation phase (hoisting, this binding) then execution phase β€” pushed onto the call stack

Full Answer

An Execution Context (EC) is the environment in which JavaScript code evaluates and executes. Every function call creates a new EC pushed onto the call stack.

Phase 1 β€” Creation Phase:

  • Scans for var declarations β†’ hoisted and set to undefined
  • Scans for let/const β†’ hoisted but placed in Temporal Dead Zone
  • Scans for function declarations β†’ fully hoisted (name + body)
  • Determines the value of this
  • Sets up the scope chain (reference to outer environment)

Phase 2 β€” Execution Phase: runs code line by line, assigns actual values.

function example() {
  // Creation phase saw: var a β†’ undefined, fn fully hoisted
  console.log(a);   // undefined (var hoisted)
  console.log(fn()); // 'works!' (function declaration hoisted)
  var a = 1;
  function fn() { return 'works!'; }
  console.log(a);   // 1 (now assigned)
}

Types of EC: Global EC (one per program), Function EC (one per call), Eval EC (avoid).

πŸ’‘ The Global EC creates the global object (window/globalThis) and binds this = global object in its creation phase.

More Core JS Questions

🟒 EasyWhat is the difference between var, let, and const?β†’πŸŸ’ EasyExplain closures with a practical example.β†’πŸŸ’ EasyWhat is hoisting in JavaScript?β†’πŸŸ’ EasyExplain the event loop, call stack, and microtask queue.β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint