Learn how to efficiently repeat actions using JavaScript loops. Explore for, while, and do...while loops with practical examples and best practices.
In programming, we often encounter situations where we need to repeat a set of instructions multiple times. JavaScript provides several loop constructs that allow us to perform repetitive tasks efficiently. In this section, we’ll explore the fundamental loop types in JavaScript: for
, while
, and do...while
. We’ll also discuss how to control loop execution using break
and continue
statements and provide practical examples, including iterating over arrays.
Loops are control structures that allow us to execute a block of code multiple times. They are essential for tasks such as processing data collections, automating repetitive tasks, and creating dynamic web content. Let’s dive into the different types of loops available in JavaScript.
for
LoopThe for
loop is one of the most commonly used loops in JavaScript. It is particularly useful when you know in advance how many times you want to execute a block of code. The for
loop consists of three parts: initialization, condition, and increment/decrement.
for
Loopfor (initialization; condition; increment) {
// Code to be executed
}
true
, the loop continues; if false
, the loop stops.for
LoopLet’s create a simple for
loop that prints numbers from 1 to 5.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Explanation:
let i = 1
sets the starting point.i <= 5
ensures the loop runs as long as i
is less than or equal to 5.i++
increases i
by 1 after each iteration.while
LoopThe while
loop is another fundamental loop type in JavaScript. It is ideal when the number of iterations is not known beforehand. The loop continues as long as the specified condition is true
.
while
Loopwhile (condition) {
// Code to be executed
}
true
, the loop executes; otherwise, it stops.while
LoopLet’s create a while
loop that prints numbers from 1 to 5.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Explanation:
i
to 1 before the loop.i <= 5
.i++
increments i
after each iteration.do...while
LoopThe do...while
loop is similar to the while
loop, but it guarantees that the loop body is executed at least once, even if the condition is false
initially.
do...while
Loopdo {
// Code to be executed
} while (condition);
do...while
LoopLet’s create a do...while
loop that prints numbers from 1 to 5.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
Explanation:
i <= 5
.JavaScript provides two statements, break
and continue
, to control the flow of loops.
break
StatementThe break
statement terminates the loop immediately, regardless of the loop condition.
break
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Exit the loop when i is 3
}
console.log(i);
}
Output:
1
2
Explanation:
i
equals 3, so numbers 1 and 2 are printed.continue
StatementThe continue
statement skips the current iteration and proceeds to the next iteration of the loop.
continue
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip the iteration when i is 3
}
console.log(i);
}
Output:
1
2
4
5
Explanation:
for
Loop: Use when you know the exact number of iterations or need to iterate over arrays or collections with a known length.while
Loop: Use when the number of iterations is not predetermined, and you need to continue until a certain condition is met.do...while
Loop: Use when you need the loop to execute at least once, regardless of the condition.Arrays are a common data structure in JavaScript, and loops are often used to iterate over their elements.
for
Loopconst fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
apple
banana
cherry
Explanation:
fruits.length
to determine the number of iterations.for...of
LoopThe for...of
loop provides a simpler syntax for iterating over iterable objects like arrays.
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
Output:
apple
banana
cherry
Explanation:
for...of
loop iterates directly over the array elements.To help you understand how loops work, let’s visualize the flow of a for
loop using a flowchart.
graph TD; A[Start] --> B[Initialization] B --> C{Condition} C -->|True| D[Execute Code Block] D --> E[Increment/Decrement] E --> C C -->|False| F[End]
Description:
for
loop: initialization, condition check, code execution, and increment/decrement.Experiment with the following code examples to reinforce your understanding:
for
Loop: Change the loop to print numbers from 10 to 1.while
Loop: Create a while
loop that prints even numbers from 2 to 10.do...while
Loop: Write a do...while
loop that prompts the user for input until they enter “stop”.break
and continue
: Use break
to exit a loop when a specific condition is met, and continue
to skip certain iterations.for
loop is ideal for known iteration counts, while the while
loop is suitable for unknown iteration counts.do...while
loop ensures the loop body executes at least once.break
statement exits a loop, while the continue
statement skips the current iteration.For more information on loops and iteration in JavaScript, check out these resources: