Following meaning

Lesson 11 Control flow

5 min read · JavaScript · Quiz

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.

coupon.js
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}
  1. Line 2 Exit 1: no code, return the cart. The finally below is never reached, so checked stays unset on this path.
  2. Line 5 Exit 2: expired coupon, return the cart. finally still runs first, so checked is set.
  3. Line 6 Exit 3: a good coupon. The function ends with no return, so the caller gets undefined. Almost certainly a bug.
  4. 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, continue and throw skip the lines after them.
  • finally runs on every path, and a return inside 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.