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.
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.
Creating a context has two phases: first declarations are registered (hoisting), then code runs line by line.
Recursion without a stopping case keeps pushing contexts until the engine throws RangeError: Maximum call stack size exceeded.
this is part of the context: for obj.method() it is obj; for a plain call in strict mode it is undefined. Arrow functions do not get their own this; they use the surrounding one.
Asynchronous callbacks (timers, events, promises) run later, in a new context, after the current stack has emptied; Level 4 covers the event loop.
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.
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}`);
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
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.
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 explanationexecution 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 predictionexecution 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.
Debuggingexecution 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 generationexecution 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 reviewexecution 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.