Following meaning

Lesson 14 State and time

5 min read · JavaScript · Quiz

stale closures, late binding in loops, order of execution

What you'll learn

  • Ask when a callback runs and which values it will see
  • Spot a loop whose callbacks all share one variable
  • Tell a stale copy from a live value

Code is read from top to bottom, but it doesn't always run that way. Timers, callbacks and promises run later, and by then the world has changed.

The idea

A function made inside another function remembers the variables around it, not the values they held at that moment. When it finally runs, later, it sees whatever those variables hold now.

Two traps follow. A loop can create many callbacks that all share one variable, so they all see its final value. And a value copied early can go stale while the real one keeps changing. Whenever you see a timer, a callback or a promise, ask: when does this run, and what will it see?

reminders.js
1function scheduleReminders(orders) {2  for (var i = 0; i < orders.length; i++) {3    setTimeout(() => {4      sendReminder(orders[i]);5    }, 1000);6  }7}89function makeCheckout(cart) {10  const total = cart.total;11  return () => charge(total);12}
  1. Line 2 var gives the whole loop one i. let would give each turn its own.
  2. Line 4 This runs a second later, after the loop has finished. By then i is orders.length, so orders[i] is undefined: a reminder to nobody.
  3. Line 10 total is copied now. If the cart changes before the callback runs, the customer is charged the old amount. Is that what you want?
  4. Line 11 The arrow function carries total with it. Ask: when does it run, and is the value still right?

Take away

  • A function remembers variables, not the values they had when it was made.
  • Ask of every callback, timer and default: when does this run, and what will it see?
  • A loop that makes functions can give them all the same variable.

Quiz: test yourself

6 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.