- A loop repeats a block of code. Each repetition is called an iteration.
- A
whileloop repeats as long as its condition is true. Use it when you don't know how many times you'll loop. - Every loop needs a start, a condition, and an update. Forget the update and you get an infinite loop.
- A
forloop puts all three in one line:for (let i = 0; i < 10; i++). Use it when you're counting. - A
do...whileloop always runs at least once. breakexits a loop immediately.continueskips to the next iteration.- Loop over a string with
for (let i = 0; i < str.length; i++)orfor (const char of str). - Watch out for off-by-one errors: indexes start at 0 and end at
length - 1. - Nested loops run the inner loop completely for each iteration of the outer loop.
- The accumulator pattern: start a variable at 0 (or
"") and add to it in each iteration.
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.