Loops: Doing Things Over and Over

Computers never get bored. Let's take advantage of that. Eleven short pages from Grade 5 of Elementary School, about 15 minutes of reading in all.

What you’ll learn

  • Why loops are a programmer's superpower
  • while loops
  • Infinite loops (and how to escape them)
  • for loops, the most common loop
  • do...while loops
  • Skipping and stopping with continue and break
  • Looping through the letters of a string
  • Loops inside loops, FizzBuzz, and a guessing game

The pages

Eleven pages, about 15 minutes.

  1. Why Loops? Picture this. You were chatting in class (again), and your teacher has given you a punishment: write "I will not talk…
  2. The while Loop The simplest loop is the while loop. It keeps repeating a block of code while a condition is true. It looks a lot like…
  3. Infinite Loops: Buggsy's Favorite Trap What happens if you forget the update? countdown stays at 5 forever. 5 > 0 is true forever. So the loop runs…
  4. The for Loop The while loop has its three ingredients scattered around: the starting point before the loop, the condition at the…
  5. The do...while Loop There's one more kind of loop, and it's a slight twist on while. A do...while loop runs the body first, and then…
  6. break and continue Sometimes you want to change how a loop behaves partway through. Two special keywords help. break stops the loop…
  7. Looping Over Strings Remember that strings have a length and each character has an index, starting from 0? That makes them perfect for…
  8. Loops Inside Loops You can put a loop inside another loop. This is called a nested loop. For every single iteration of the outer loop…
  9. The Classic: FizzBuzz There's a famous little programming challenge called FizzBuzz. It's been used for years in job interviews, because…
  10. Mini Project: The Number Guessing Game Let's build a proper game! The computer picks a secret number from 1 to 100, and you have to guess it. After each…
  11. Recap The key ideas of Grade 5, JavaScript loops, on one page. A loop repeats a block of code. Each repetition is called an…

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