for
, while
, and do...while
LoopsLoops are fundamental in JavaScript for running the same block of code multiple times. The three main types — for
, while
, and do...while
— each have their own syntax and best use cases.
for
LoopThe for
loop is great when you know how many times you want to run the loop, such as counting up or down.
Syntax:
for (initialization; condition; update) {
// code to run
}
Example: Counting up from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1 2 3 4 5
Example: Counting down from 5 to 1
for (let i = 5; i >= 1; i--) {
console.log(i);
}
// Output: 5 4 3 2 1
while
LoopUse a while
loop when you want to run code as long as a condition remains true, but you might not know in advance how many times it will run.
Syntax:
while (condition) {
// code to run
}
Example: Counting up until a condition changes
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
// Output: 1 2 3 4 5
do...while
LoopThe do...while
loop guarantees the code inside runs at least once, then continues as long as the condition is true.
Syntax:
do {
// code to run
} while (condition);
Example: Run code once, then repeat while condition holds
let count = 1;
do {
console.log(count);
count++;
} while (count <= 5);
// Output: 1 2 3 4 5
for
loops when you know the exact number of iterations.while
loops when the number of iterations depends on a dynamic condition.do...while
loops when you need to run the code block at least once before checking the condition.Understanding these loops lets you handle many repetitive tasks efficiently, from counting and iterating over data to waiting for certain conditions in your program.
break
and continue
When working with loops, sometimes you want to control the flow more precisely—either stop the loop early or skip certain iterations. JavaScript provides two keywords to help with this: break
and continue
.
break
— Exit the Loop Early
The break
statement immediately stops the entire loop and exits it, no matter where it is in the loop cycle.
Example: Exit loop when a specific number is found
for (let i = 1; i <= 10; i++) {
if (i === 5) {
console.log("Number 5 found, stopping loop.");
break; // Exit loop here
}
console.log(i);
}
// Output:
// 1
// 2
// 3
// 4
// Number 5 found, stopping loop.
In this example, the loop stops as soon as it reaches number 5.
continue
— Skip the Current Iteration
The continue
statement skips the rest of the code in the current loop iteration and immediately moves to the next one.
Example: Skip even numbers in a range
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}
// Output: 1 3 5 7 9
Here, whenever the number is even, continue
skips the console.log(i)
statement, so only odd numbers are printed.
Summary
break
to stop the loop completely when a condition is met.continue
to skip certain iterations but keep the loop running.These control statements give you flexible ways to manage loops, making your code more efficient and easier to read.
Loops are powerful tools that let you repeat tasks efficiently. Here are some common patterns you’ll encounter when working with loops, along with clear examples.
An accumulator keeps a running total (or result) that updates each time the loop runs. This is useful for adding up numbers or combining data.
let sum = 0; // Initialize accumulator
for (let i = 1; i <= 5; i++) {
sum += i; // Add current number to sum
}
console.log("Sum of numbers 1 to 5 is:", sum);
// Output: Sum of numbers 1 to 5 is: 15
Loops can also count down from a starting number to zero, useful for timers or countdown displays.
let countdown = 5;
while (countdown > 0) {
console.log("Countdown:", countdown);
countdown--; // Decrement the counter
}
console.log("Liftoff!");
// Output:
// Countdown: 5
// Countdown: 4
// Countdown: 3
// Countdown: 2
// Countdown: 1
// Liftoff!
You can use loops to create or transform arrays by adding items one by one.
let numbers = [1, 2, 3, 4, 5];
let squares = []; // Empty array to store results
for (let i = 0; i < numbers.length; i++) {
squares.push(numbers[i] * numbers[i]); // Square each number and add to new array
}
console.log("Squares:", squares);
// Output: Squares: [1, 4, 9, 16, 25]
These patterns are essential building blocks for solving many programming problems and will help you write efficient, readable code.