Control Flow and Stepping Through Code with Breakpoints
Write a loop with guards, watch it produce the wrong answer, and find the bug by pausing the program at a breakpoint instead of guessing.
Contentsand lesson path
On this page
- The problem
- Step 1: write the first version and run it
- Step 2: stop at a breakpoint
- Step 3: fix and rerun
- Other ways to branch
- Check your understanding
- Apply it
- Review prompt
Lessons of JavaScript Foundations
- Values, Types and the Rules of Coercion Concept · 20 min
- Control Flow and Stepping Through Code with Breakpoints Worked example · 20 min
- Functions, Scope and Closures Concept · 25 min
- Shaping Data with Objects, Arrays, Map and Set Worked example · 30 min
- Classes, this, Modules and Errors Concept · 25 min
- Check: Predict the Output, Then Pass the Kata Tests Knowledge check · 8 questions
What you will learn
- Write programs with variables, operators, conditionals and loops, predicting the result of type coercion and of strict vs loose equality.
01. The problem
Control flow is the order in which your statements run. So far the programs in this skill have run top to bottom; real programs decide. if and else choose between paths, loops repeat work, and break and continue let a loop stop early or skip a pass. Bugs love decisions: a condition that is one character off still runs, it just runs the wrong statements.
This lesson is a worked example with a real bug. We have an array of electricity readings from a smart meter: an hour of the day and the energy used, both sometimes arriving as strings or null. The rules of the report are:
- a reading whose
hourisnullis the end-of-day marker: stop, do not read further; - a reading whose
kwhisnullis a sensor glitch: skip it, keep going; - hours 7 to 19 are peak tariff, the rest are off-peak;
- the day after the marker is a different day, so anything after it must not be counted.
02. Step 1: write the first version and run it
Here is a first version. Before you read on, do what pays off before running any code with decisions in it: predict the output by hand. The valid readings are 0.4 at hour 1, 1.2 at hour 8, 2.1 at hour 18 and 0.6 at hour 22, so peak should be 3.30 and off-peak 1.00.
// Tariff model: hours 7 to 19 are peak, the rest are off-peak.
const readings = [
{ hour: 1, kwh: '0.4' },
{ hour: 8, kwh: '1.2' },
{ hour: 14, kwh: null },
{ hour: 18, kwh: '2.1' },
{ hour: 22, kwh: '0.6' },
{ hour: null, kwh: '0.0' },
{ hour: 3, kwh: '9.9' },
];
let peak = 0;
let offPeak = 0;
for (const r of readings) {
if (r.hour === null) break; // end-of-day marker
if (r.kwh === null) continue; // skip a glitched reading
const kwh = Number(r.kwh);
if (r.hour >= 7 && r.hour <= 19) {
peak += kwh;
}
offPeak += kwh; // BUG: every reading lands here too
}
console.log(`peak ${peak.toFixed(2)} kWh, off-peak ${offPeak.toFixed(2)} kWh`);peak 3.30 kWh, off-peak 4.30 kWhPeak is right and off-peak is not: 4.30 is peak plus off-peak. Somewhere, a reading is being added to both totals. The comment even says so — but in real life there is no comment, and there may be hundreds of lines between the two totals. You could add console.log to every branch, or you could stop the program where the damage happens and look around.
03. Step 2: stop at a breakpoint
A breakpoint tells the debugger: "pause the program when it reaches this line, before running it". While paused you can read every variable in scope, then take a single step or continue. Browsers pause on a debugger statement or on a line you click in DevTools; Node.js ships the same inspector with a terminal interface, node inspect (the transcript below is from Node 22.23; other current versions print the same commands and pauses). Start it like this and press c (continue) when it stops on the first line:
The transcript below is real output, with the lines of code context that the debugger prints around each pause removed for space. watch adds an expression that is shown at every pause, sb(20) sets a breakpoint on line 20, the peak += kwh; line, and each c continues until the next pause.
$ node inspect energy.js
< Debugger listening on ws://127.0.0.1:9229/<id>
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
debug> Break on start in energy.js:2
debug> watch('r.hour')
debug> watch('peak')
debug> sb(20)
debug> c
break in energy.js:20
Watchers:
0: r.hour = 8
1: peak = 0
debug> c
break in energy.js:20
Watchers:
0: r.hour = 18
1: peak = 1.2
debug> c
< peak 3.30 kWh, off-peak 4.30 kWhLine 20 ran exactly twice: once for hour 8 with peak still 0, once for hour 18 with peak at 1.2. Those are the two peak readings, so line 20 itself behaves. The question is what runs after it — and the n (next) command would step you to line 22, offPeak += kwh;, for both hours. Two lines of watching answer what a page of guessing would not.
04. Step 3: fix and rerun
The diagnosis: offPeak += kwh; sits outside the if, so every valid reading — peak or not — falls through to it. The two branches were meant to be exclusive, which in code is spelled else.
if (r.hour >= 7 && r.hour <= 19) {
peak += kwh;
} else {
offPeak += kwh;
}peak 3.30 kWh, off-peak 1.00 kWhBoth totals now match the hand prediction, including the guards: the glitched reading at hour 14 was skipped by continue, the marker stopped the loop before the hour-3 reading of a different day could be counted, and break left the loop cleanly. That last property is worth naming: control flow is also how you make data trustworthy — skip what is broken, stop at the boundary you defined.
05. Other ways to branch
Two more forms cover the rest of everyday control flow. switch compares one value against several exact cases and reads better than a ladder of == checks; each case needs a break (or a return, as here) or execution falls through into the next case, which is occasionally useful and usually a bug. The ternary operator condition ? a : b is an expression, so it fits where a statement would not, such as inside a template literal or a map callback.
function statusText(code) {
switch (code) {
case 'ok':
return 'reading looks healthy';
case 'glitch':
case 'stale':
return 'check the sensor';
default:
return 'unknown code';
}
}
const readings = [{ code: 'ok' }, { code: 'stale' }, { code: 'wibble' }];
for (const r of readings) {
console.log(r.code, '->', statusText(r.code));
}
const ok = readings.filter((r) => statusText(r.code) === 'reading looks healthy');
console.log(ok.length === 1 ? '1 healthy reading' : `${ok.length} healthy readings`);ok -> reading looks healthy
stale -> check the sensor
wibble -> unknown code
1 healthy reading06. Check your understanding
07. Apply it
Take a small script of your own, or reuse the energy file, and:
- Add a rule: readings above 3 kWh are spikes that must be reported but not included in either total. Decide whether that is a
continue, a branch or a separate list, and say why in a comment. - Plant a subtle bug in your own copy — swap a
continuefor abreak, or drop anelse— run it, and find the bug again withnode inspect, a breakpoint and one watcher. Noconsole.logallowed. - Rewrite one
if/elseladder over exact values as aswitch, and oneswitchas a ternary, keeping the output identical.
Stepping through code with breakpoints is the same skill in the browser: the DevTools workflow for a broken stylesheet, which the css-fundamentals skill ends with, follows the same pause-and-inspect rhythm. The DOM and events skill that comes next adds the event handlers where control flow meets the user.
08. Review prompt
Without looking back: say in one sentence each what break, continue and return do from inside a loop. Then describe the three debugger commands used here and what each shows, and explain why the first version double-counted peak hours while the fixed one cannot. Finally, name one situation where switch reads better than an if/else ladder and one where a ternary fits better than either.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.