We'll kick things off with a basic recursive function: calculating the factorial of a number.
function factorial(n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// Call the function to start the trace
console.log(factorial(5)); // Should print 120
Ctrl + Shift + I
(Windows/Linux) or Cmd + Option + I
(Mac).Ensure your JavaScript loads correctly in the browser. Placing your code in an HTML file might be a tidy way to do this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Recursive Function Debugging</title>
</head>
<body>
<script src="your-script-file.js"></script>
</body>
</html>
Go to the Sources
panel in Developer Tools and find your JavaScript file.
Click the line number where you want the breakpoint. For example, set it inside the factorial
function:
Click on the line with if (n <= 1) {
.
Set a breakpoint within the recursive function and call it to see the function call stack.
With your breakpoint in place, refresh the page or call the function from the console, like this: factorial(5);
.
When the breakpoint hits, the execution pauses, and you can see the current state in the Call Stack
section.
Step Through: Use the controls to navigate through your code. Step Into
(F11) helps with entering recursive function calls.
Step Over (F10)
: Runs the next line without diving into functions.Step Into (F11)
: Enters into function calls on the current line, vital for following recursive calls.Step Out (Shift + F11)
: Completes the current function and moves back to the caller.Inspect Variables: As you step through, watch the variables’ values in the Scope
section. For the factorial
function, see how n
changes with each call.
Add n
to the Watch
panel to monitor its value.
You can add custom expressions:
factorial(n - 1)
to see results of subsequent recursive calls.Inline Debugging: Hover over variables to see their values.
Scope: Check Local
and Global
scope to understand variable values and contexts at each call level.
If the stack depth seems off or recursion doesn't stop, these steps will help find the problem.
Look for repeated or unexpected values in n
to diagnose logic issues at each step.
Let's trace factorial(5)
:
factorial(5)
stops at the breakpoint.n = 5
; move to the next line (return n * factorial(n - 1);
).factorial(4)
.n = 4
; repeat until n = 1
.The Call Stack
should display entries for factorial(5)
, factorial(4)
, factorial(3)
, factorial(2)
, and factorial(1)
.
After analyzing the recursion:
Resume Script Execution (F8)
button to let the script run to completion.When you spend some time observing recursive functions, you'll truly start appreciating the depth (pun intended) of how they operate. The more you practice, the sharper your debugging skills will become with these tools!