Loops in JavaScript: for, while, do while
#Loops in JavaScript: for, while, do while
Loops are a fundamental concept in programming that allow you to execute a block of code multiple times. JavaScript provides several types of loops to handle different situations.
In this tutorial, we’ll cover the most commonly used loop structures: for
, while
, and do...while
.
The for
loop is used when the number of iterations is known beforehand.
for (initialization; condition; increment) {
// code to execute
}
for (let i = 1; i <= 5; i++) {
console.log("Iteration " + i);
}
This loop will run 5 times, printing the iteration number.
The while
loop is used when the number of iterations is not known in advance. It continues as long as the condition is true.
while (condition) {
// code to execute
}
let count = 1;
while (count <= 5) {
console.log("Count is: " + count);
count++;
}
The do...while
loop is similar to the while
loop, but it ensures the code block runs at least once, even if the condition is false.
do {
// code to execute
} while (condition);
let number = 1;
do {
console.log("Number: " + number);
number++;
} while (number <= 5);
break
Used to exit the loop prematurely.
for (let i = 1; i <= 10; i++) {
if (i === 6) break;
console.log(i);
} // Outputs 1 to 5
continue
Skips the current iteration and continues with the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
} // Outputs 1, 2, 4, 5
✅ Use for
when you know how many times to loop.
✅ Use while
or do...while
when the loop should run based on a condition.
✅ Avoid infinite loops by ensuring the condition eventually becomes false.
✅ Use break
and continue
to manage loop flow carefully.
Loops are crucial for repeating tasks efficiently. By mastering for
, while
, and do...while
loops in JavaScript, you’ll gain greater control over your code’s behavior and structure.
Practice different types of loops and experiment with nested loops and loop control statements to become more confident in your coding skills.