Skip to main content

Introduction to Loops

Loops offer a quick and easy way to do something repeatedly in JavaScript.

1. for Loop

The most traditional loop. It repeats until a specified condition evaluates to false. It requires three standard expressions: (initialization; condition; afterthought).

for (let i = 0; i < 5; i++) {
console.log(`Iteration number: ${i}`);
}

2. while Loop

Executes its statements as long as a specified condition evaluates to true. It's useful when you don't know ahead of time exactly how many times the loop should run.

let count = 0;

while (count < 3) {
console.log(`Count is: ${count}`);
count++; // CRITICAL: don't forget to break the condition or it loops forever!
}

3. do...while Loop

Similar to the while loop, but the condition is evaluated after executing the statement. This guarantees that the loop runs at least once!

let count = 10;

do {
console.log("This will print exactly once.");
count++;
} while (count < 5);