For Loop:
The for
loop is used when you know beforehand how many times you want to iterate.
// Example of a for loop for (let i = 0; i < 5; i++) { console.log(i); // Outputs 0, 1, 2, 3, 4 }
While Loop:
The while
loop is used when you want to execute a block of code as long as a condition is true. It’s suitable when you don’t know how many times you’ll iterate beforehand.
// Example of a while loop let j = 0; while (j < 5) { console.log(j); // Outputs 0, 1, 2, 3, 4 j++; }
Do-While Loop:
The do-while
loop is similar to a while
loop, but it ensures that the block of code executes at least once before checking the condition.
// Example of a do-while loop let k = 0; do { console.log(k); // Outputs 0, 1, 2, 3, 4 k++; } while (k < 5);
In each example:
- The
for
loop initializes a variable (i
), checks a condition (i < 5
), executes a block of code (console.log(i)
), and increments (i++
) after each iteration. - The
while
loop checks a condition (j < 5
), executes a block of code (console.log(j)
), and increments (j++
) inside the loop. - The
do-while
loop executes the block of code (console.log(k)
), increments (k++
), and then checks the condition (k < 5
).