A loop repeats a block of code multiple times, so you don't have to write it out by hand. Loops are how programs process lists of data, repeat a task a fixed number of times, or keep running until some condition is met.
Use a for loop when you know how many times you want to repeat something.
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
// Prints Count: 1 through Count: 5A for loop has three parts, separated by semicolons: a starting point (let i = 1), a condition checked before every repeat (i <= 5), and a step that runs after every repeat (i++).
Use a while loop when you don't know in advance how many repeats you need — it keeps going as long as a condition stays true.
let energy = 3;
while (energy > 0) {
console.log("Still going, energy: " + energy);
energy = energy - 1;
}If the condition in a while loop never becomes false, the loop runs forever — this is called an infinite loop, and it's one of the most common early mistakes. Always make sure something inside the loop moves it toward finishing.
for...of is the simplest way to visit every item in a list.
let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
console.log(fruit);
}