Following meaning
Lesson 11 Control flow
draw the paths, exceptions as jumps
What you'll learn
- Count the exits of a function, including falling off the end
- Follow jumps like return, break, throw and finally
- Spot swallowed errors and returns that hide results
A function can leave in more ways than you think. The bug is usually on a path the AI never looked at.
The idea
To read control flow, draw the paths. Every function has exits: a return, a throw, or falling off the end, which quietly returns undefined. Count them, then ask what the caller gets on each one.
Watch for jumps. return, break, continue and throw all skip the lines after them. finally runs on every path, even right before a return. And a return inside finally wins over everything, even an error.
1function applyCoupon(cart, code) {2 if (!code) return cart;3 try {4 const coupon = lookupCoupon(code);5 if (coupon.expired) return cart;6 cart.total -= coupon.amount;7 } catch (err) {8 console.log("bad coupon");9 } finally {10 cart.checked = true;11 }12}
- Line 2 Exit 1: no code, return the cart. The
finallybelow is never reached, socheckedstays unset on this path. - Line 5 Exit 2: expired coupon, return the cart.
finallystill runs first, socheckedis set. - Line 6 Exit 3: a good coupon. The function ends with no
return, so the caller getsundefined. Almost certainly a bug. - Line 8 Exit 4: the error is logged and swallowed. Also
undefined. The caller can't tell a bad coupon from a good one.
Take away
- Count the exits: return, throw, and falling off the end.
return,break,continueandthrowskip the lines after them.finallyruns on every path, and areturninside it hides everything else.
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.