Loops
Loops are one of the most powerful tools in programming. They let you process lists, count items, repeat animations, and much more — all automatically.
The for Loop
The classic for loop runs a fixed number of times:
for (let i = 0; i < 5; i++) {
console.log("Count: " + i);
}
// Count: 0
// Count: 1
// Count: 2
// Count: 3
// Count: 4
The three parts inside the parentheses:
let i = 0— start: initialise the counteri < 5— condition: keep looping while this is truei++— update: run after each loop
Counting backwards works the same way:
for (let i = 5; i > 0; i--) {
console.log(i);
}
// 5, 4, 3, 2, 1
Looping Over an Array
Use the index to access each item in an array:
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// apple
// banana
// cherry
for...of
for...of is a cleaner way to loop over arrays when you don't need the index:
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// cherry
Use for...of when you want each item. Use a regular for loop when you need the index number (position) of the item.
for...in
for...in loops over the keys of an object:
const user = {
name: "Alice",
age: 25,
city: "London",
};
for (const key in user) {
console.log(key + ": " + user[key]);
}
// name: Alice
// age: 25
// city: London
The while Loop
A while loop keeps running as long as a condition is true:
let count = 0;
while (count < 5) {
console.log("Count: " + count);
count++;
}
Use while when you don't know in advance how many times to loop:
// Keep guessing until you get it right
let guess = 0;
const secret = 7;
while (guess !== secret) {
guess = Math.floor(Math.random() * 10);
console.log("Guessed: " + guess);
}
console.log("Got it!");
Always make sure the condition in a while loop will eventually become false, or your code will loop forever and freeze the page. This is called an infinite loop.
break and continue
Control the flow of a loop with break and continue:
// break — exit the loop early
for (let i = 0; i < 10; i++) {
if (i === 5) break; // stops when i is 5
console.log(i); // prints 0, 1, 2, 3, 4
}
// continue — skip to the next iteration
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
console.log(i); // prints 1, 3, 5, 7, 9
}
Try It Yourself
Have anything to say about this lesson?
Your feedback helps improve these tutorials. If something was confusing or missing, let us know.