What Are Loops in JavaScript?
The for loop is ideal when you know how many times you want to repeat an action. It combines initialization, condition checking, and increment/decrement in one concise statement.
Basic For Loop Syntax
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5
Breaking it down:
<ul>
<li><strong>let i = 1</strong> → Start counting at 1</li>
<li><strong>i <= 5</strong> → Keep going until 5</li>
<li><strong>i++</strong> → Add 1 each time (<code>i++</code> means <code>i = i + 1</code>)</li>
</ul>
Example 2: Print "Hello" 3 Times
for (let i = 1; i <= 3; i++)
{ console.log("Hello!"); }
// Output:
// Hello!
// Hello!
// Hello!
A while loop keeps running as long as a condition is true. Use it when you don't know exactly how many times to loop
Syntax:
while (condition is true) {
// Code to repeat
// Don't forget to update the condition!
}
Example : Count to 3 with While
let count = 1;
while (count <= 3) {
console.log(count);
count++; // Very important! Without this, loop never stops
}
// Output:
// 1
// 2
// 3
A do-while loop runs the code at least once, then checks the condition.
Example :
do {
console.log(number);
number++;
} while (number < 5);
// Output: 10
// Runs once even though 10 is not less than 5!
When to use do-while:
<ul>
<li>Showing a menu at least once</li>
<li>Getting user input at least once</li>
<li>Running code before checking a condition</li>
</ul>
The break statement stops the loop immediately and exits.
Example:
let numbers = [3, 7, 12, 5, 9];
for (let i = 0; i < numbers.length; i++) {
console.log("Checking: " + numbers[i]);
if (numbers[i] === 12) {
console.log("Found 12! Stopping search.");
break; // Exit the loop
}
}
// Output:
// Checking: 3
// Checking: 7
// Checking: 12
// Found 12! Stopping search.
// (Doesn't check 5 or 9)
The continue statement skips the current iteration and moves to the next one.
Example: Print Only Odd Numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}
// Output: 1, 3, 5, 7, 9
What's happening:
<ul>
<li>When <code>i</code> is 2, 4, 6, 8, or 10, the <code>continue</code> statement skips <code>console.log</code></li>
<li>Only odd numbers get printed</li>
</ul>