JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 10: Scope and JavaScript BehaviorLesson 50 of 150About 45 minutes

Lesson 50: Understanding execution contexts

01Opening question

When an error says "at total (line 3) at checkout (line 8)", what is that list, and why is it in that order?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Each call pauses the caller until the called function returns.

function inner() {
  console.log("3. inner runs");
}
function outer() {
  console.log("2. outer starts");
  inner();
  console.log("4. outer ends");
}
console.log("1. start");
outer();
console.log("5. done");

03Objective and prerequisites

Learning objective: Describe execution contexts and the call stack, read a stack trace, trace nested calls, and explain how this is set for regular and arrow functions.

You need: Lesson 47: Lexical environments, Lesson 49: Hoisting and the temporal dead zone, Lesson 37: Properties, methods and dynamic keys

Skills practised: Execution contexts and the call stack.

04Explanation

An execution context is the environment for running one piece of code: the global code, or one function call. It holds that call's variables, its link to outer scopes and its value of this.

The call stack keeps track of running contexts. Calling a function pushes a new context on top; returning pops it off and the caller continues.

Only the context at the top of the stack runs. That is why the outer function waits while the inner one runs.

A stack trace in an error message lists the contexts on the stack when the error happened, newest first.

05Definitions

Execution context
The environment in which one piece of code runs: its variables, scope link and this.
Call stack
The stack of execution contexts for functions that are currently running.
Stack trace
The list of calls active when an error occurred, newest first.
Stack overflow
A RangeError when too many nested calls fill the call stack.
this
A value set per call: the object before the dot for methods, undefined for plain strict calls, inherited by arrow functions.

Open the full glossary

06Visual learning object

Call stack and scope explorer. Step through nested calls and watch contexts push onto and pop off the stack.

Loading the interactive object…

Open the full Scope chain explorer page with its guided experiment.

07Examples

ex-050-01Call stack order Browser-executable JavaScript

The caller waits until the called function returns.

const log = [];
function c() { log.push("c"); }
function b() { log.push("b start"); c(); log.push("b end"); }
function a() { log.push("a start"); b(); log.push("a end"); }
a();
console.log(log.join(" > "));
Sample input
None
Expected output
a start > b start > c > b end > a end
Common mistake
Expecting a end to happen before b finishes.
Try this
Add a function d called from c and predict the new order.
Source
examples/ex-050-01-stack-order.js (repository pending publication)

ex-050-02Measure the stack depth Browser-executable JavaScript

Each nested call adds one context.

let depth = 0;
let maxDepth = 0;
function enter(levels) {
  depth++;
  maxDepth = Math.max(maxDepth, depth);
  if (levels > 0) enter(levels - 1);
  depth--;
}
enter(4);
console.log(maxDepth, depth);
Sample input
None
Expected output
5 0
Common mistake
Forgetting the stopping case, which overflows the stack.
Try this
Call enter(10) and predict maxDepth.
Source
examples/ex-050-02-depth.js (repository pending publication)

ex-050-03Stack overflow Browser-executable JavaScript

Calls without a stopping case fill the stack.

function forever(n) {
  return forever(n + 1);
}
try {
  forever(0);
} catch (e) {
  console.log(e.name);
}
Sample input
None
Expected output
RangeError
Common mistake
Writing recursion without a base case.
Try this
Add a stopping case at n === 100 and return n.
Source
examples/ex-050-03-stack-overflow.js (repository pending publication)

ex-050-04How this is set Browser-executable JavaScript

The call decides this for regular functions; arrows inherit it.

const timer = {
  label: "Tea",
  regular() { return this.label; },
  nested() {
    const arrow = () => this.label;
    return arrow();
  }
};
const loose = timer.regular;
console.log(timer.regular());
console.log(timer.nested());
try {
  loose();
} catch (e) {
  console.log(e.name);
}
Sample input
None
Expected output
Tea Tea TypeError
Common mistake
Taking a method off its object and expecting this to stay attached.
Try this
Use loose.call(timer) and predict the output.
Source
examples/ex-050-04-this-binding.js (repository pending publication)

ex-050-05Each context has its own variables Browser-executable JavaScript

Recursive calls do not share locals.

function countdown(n) {
  const label = `T-${n}`;
  if (n === 0) return [label];
  return [label, ...countdown(n - 1)];
}
console.log(countdown(3));
Sample input
None
Expected output
["T-3", "T-2", "T-1", "T-0"]
Common mistake
Expecting label to be overwritten by the deeper calls.
Try this
Return the labels in increasing order.
Source
examples/ex-050-05-context-variables.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Add the stopping case

Stop recursion before it overflows the stack.

function sumTo(n) {
  return n + sumTo(n - 1);
}
let result;
try { result = sumTo(4); } catch (e) { result = e.name; }
console.log(result);

Record the call order

Trace pushes and pops on the call stack.

const trace = [];
function load() {
  trace.push("load in");
  parse();
  trace.push("load out");
}
function parse() {
  trace.push("parse");
}
// TODO: call load, then set order to the array you expect trace to equal
const order = [];
console.log(order.join(", "));

Call logger

Wrap functions to show nesting depth like a call stack.

// Write traced(name, fn) and a shared log array

09Prediction

Commit to an answer first, then run the real code to compare.

function a() { return b() + 1; }
function b() { return c() * 2; }
function c() { return 3; }
console.log(a());

What is printed?

10Debugging investigation

Folder size calculation overflows the stack

Calculating the size of a folder tree throws RangeError: Maximum call stack size exceeded instead of returning 60.

const root = { size: 10, children: [{ size: 20, children: [] }, { size: 30, children: [] }] };
function totalSize(folder) {
  let sum = folder.size;
  for (const child of folder.children) sum += totalSize(folder);
  return sum;
}
let total;
try { total = totalSize(root); } catch (e) { total = e.name; }
console.log(`Total: ${total}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Reading a stack trace

A bug report includes an error with a stack trace: the top line is where the error happened, and each line below is the function that called it. Reading it from top to bottom walks back through the call stack to the user action that started it.

function parsePrice(text) {
  if (Number.isNaN(Number(text))) throw new Error(`Bad price: ${text}`);
  return Number(text);
}
function addItem(text) { return parsePrice(text); }
try { addItem("ten"); } catch (e) { console.log(e.message); }

12Knowledge check

1. What happens to the call stack when a function returns?

  • A context is pushed
  • Its context is popped and the caller continues
  • The stack is cleared
  • Nothing

2. What is printed?

function g() { console.log(3); }
function f() { console.log(1); g(); }
f();
console.log(2);
  • 1 2 3
  • 1 3 2
  • 2 1 3
  • 3 2 1

3. In a stack trace, which line shows where the error happened?

  • The bottom line
  • The top line
  • The middle
  • It is not shown

4. Why does this throw RangeError: Maximum call stack size exceeded?

function down(n) { return down(n - 1); }
down(5);
  • There is no stopping case
  • n is const
  • Recursion is not allowed
  • The return is missing a semicolon

5. What is printed?

const o = { label: "Box", show() { const f = () => this.label; return f(); } };
console.log(o.show());
  • Box
  • undefined
  • An error
  • label

6. A deeply nested category tree has unknown depth. Which is safer for very deep trees?

  • Recursion with no limit
  • A loop with an explicit stack array
  • Copying the tree with JSON
  • Using var

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Add the stopping case: Prints 10; sumTo(100)
  • Record the call order: Prints the order; Matches the real trace
  • Call logger: Prints result and log; Passes arguments
  • ex-050-01: output matches the documented expected output
  • ex-050-02: output matches the documented expected output
  • ex-050-03: output matches the documented expected output
  • ex-050-04: output matches the documented expected output
  • ex-050-05: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-10-scope-and-javascript-behavior/lesson-050-understanding-execution-contexts/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • An execution context holds one call's variables, scope link and this.
  • The call stack pushes on call and pops on return.
  • Stack traces list active calls, newest first.
  • Recursion needs a stopping case; arrows inherit this.

Suggested next lesson

Lesson 51: Understanding the DOM tree planned

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation execution contexts and the call stack
Context: I am learning execution contexts and the call stack in JavaScript.
Task: Explain execution contexts, the call stack and stack traces with a three-function example, and how this is set.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction execution contexts and the call stack drill
Context: I have practised execution contexts and the call stack.
Task: Give me six snippets with nested calls, recursion and this, and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging execution contexts and the call stack bug
Context: My recursive function throws Maximum call stack size exceeded.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation execution contexts and the call stack practice
Context: I finished the execution contexts and the call stack exercises.
Task: Create three exercises that trace call order and fix recursion.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review execution contexts and the call stack review
Context: Here is my code that uses execution contexts and the call stack.
Task: Review my recursive and method-heavy code for stack and this problems.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.