Loops
for, while, do…while, for…of, for…in, break and continue.
Loops repeat code: print a times table, add up a shopping cart, process every row of data. JavaScript has several loops, each suited to a different job.
The classic for loop#
The three parts inside the parentheses are:
- Initialiser —
let i = 1runs once before the loop. - Condition —
i <= 5is checked before each iteration; the loop stops when it's falsy. - Update —
i++runs after each iteration.
Use let (not const) for the counter, since it changes. Counting down or in steps works the same way:
Looping over an array by index
Note i < lessons.length, not <=. Arrays start at index 0, so the last index is length - 1. Getting this wrong is the famous off-by-one error.
for...of: loop over values#
When you don't need the index, for...of is cleaner. It works with arrays, strings, Maps, Sets and anything iterable:
Need the index too? Use entries() with destructuring:
for...in: loop over object keys#
Don't use
for...inon arrays. It iterates keys as strings ("0","1"…) and can include inherited properties. For objects, many developers preferfor (const [key, value] of Object.entries(obj)), which you'll see in the objects lessons.
while: loop until something changes#
Use while when you don't know in advance how many iterations you need:
Make sure something inside the loop eventually makes the condition false — otherwise you've written an infinite loop and the page or process will freeze.
do...while: run at least once#
The body runs first, then the condition is checked — ideal for "try, then check" logic like retrying input.
break and continue#
Breaking out of nested loops with labels
Labels are rare; often it's cleaner to move the loops into a function and return.
Nested loops: a times table#
Loops vs array methods#
For arrays, you'll often use methods like forEach, map, filter and reduce instead of hand-written loops:
These are covered in Array methods. Plain loops are still the right tool when you need break, await inside the loop, or maximum performance.
Which loop should I use?#
Common mistakes#
- Off-by-one:
i <= arr.lengthreads past the end (givingundefined). - Infinite loops: forgetting to update the variable in a
while. - Using
for...inon an array. - Using
var iin loops that create callbacks — every callback sees the final value.letcreates a freshiper iteration (you'll see why in Scope & closures).
What's next#
You can now repeat work. Next, you'll package logic into reusable functions.
Check your understanding
Quick quiz
1.Which loop is the best fit for going through the *values* of an array?
2.How many times does
do { n++; } while (false);run its body?3.What does
continuedo inside a loop?
Finished reading?
Mark this lesson complete to track your progress.