45 Mins beginner
6. Loops
Iteration
Loops
Loops allow you to run the same block of code multiple times. Computers excel at repetitive tasks, and loops are how we trigger them.
๐ The For Loop
A for loop is used when you know exactly how many times you want the code to run. It consists of an initializer, a condition, and an incrementer.
for (let i = 1; i <= 5; i++) {
console.log("Iteration number:", i);
}
OutputIteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
๐ The While Loop
A while loop runs continuously as long as its condition remains true. Use it when you don't know how many iterations are needed.
let countdown = 3;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
console.log("Liftoff!");
Output3
2
1
Liftoff!
2
1
Liftoff!
โญ๏ธ Break and Continue
break instantly destroys the loop. continue skips the rest of the current cycle and jumps to the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
if (i === 5) {
break;
}
console.log(i);
}
Output1
2
4
2
4
Knowledge Check
Ready to test your understanding of 6. Loops?