Infinite Loops: Buggsy's Favorite Trap

Grade 5, page 3 of 11. A one-minute read.

What happens if you forget the update?

JavaScriptHas a bug
let countdown = 5;

while (countdown > 0) {
  console.log(countdown);
  // oops! forgot countdown--
}

countdown stays at 5 forever. 5 > 0 is true forever. So the loop runs... forever. It prints 5, 5, 5, 5, 5... until the end of time, or until your computer gives up. This is called an infinite loop.

Watch outEscaping an infinite loop

Every programmer writes an infinite loop eventually. It's practically a rite of passage. If it happens to you:

  • In the browser: the tab will freeze. Close the tab (or the whole browser if you have to). Some browsers will offer to stop the script for you.
  • In Node.js: press Ctrl + C in the terminal to stop the program.

Then find your loop and make sure the condition will eventually become false. Usually you forgot to update a variable, or you're updating it in the wrong direction (like countdown++ when you meant countdown--).

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning