Loops
Loops allow you to execute a block of code multiple times, which is useful when you need to repeat actions like traversing arrays or iterating through conditions.
for
loopwhile
loopdo...while
loopfor
LoopThe for
loop is the most commonly used loop to iterate through arrays or perform a block of code a specific number of times.
for(initialization; condition; increment/decrement) {
// code block to be executed
}
for (let i = 1; i <= 5; i++) {
console.log(i);
}
while
LoopThe while
loop will continue to run as long as the condition is true. It's useful when you donβt know how many times you need to iterate in advance.
while (condition) {
// code block to be executed
}
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
do...while
LoopThe do...while
loop executes the code block once before checking the condition. It guarantees the block runs at least once.
do {
// code block to be executed
} while (condition);
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
for
, while
, and do...while
. Choose the one that fits your needs based on how you want the loop to behave.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!