Basics
Loops: for, while, do-while
Repeat a block of code while a condition is true.
1. Explanation
for is the most common loop when you know the count. while runs as long as the condition is true. do-while runs the body at least once. Modern JS adds for...of (iterates values of an array) and for...in (iterates object keys). Use break to exit and continue to skip to the next iteration.
2. Example
Try it yourself
Console
Click Run to see output.
3. Expected output
output
i = 1
i = 2
i = 3
i = 4
i = 5
n 0
n 1
n 2
apple
banana
mango4. Common mistakes
- ✗Off-by-one errors: i < arr.length vs i <= arr.length
- ✗Creating infinite loops by forgetting to update the counter
- ✗Using for...in on an array — returns indexes as strings, prefer for...of
5. Practice questions
- Print all even numbers from 1 to 50
- Print the multiplication table of 7
- Sum the digits of a number using a while loop