Loops (for, while, do-while)
Loops are essential for executing the same code multiple times, allowing you to automate repetitive tasks in your programs. JavaScript provides several types of loops, including the for
loop, while
loop, and do-while
loop.
1. The for
Loop
The for
loop is commonly used when you know the number of iterations in advance. It has the following structure:
for (initialization; condition; update) {
// Code to execute in each iteration
}
Here's an example that prints numbers from 1 to 5:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
In this example, i
is the loop variable. The loop starts with i
being 1, and in each iteration, i
is incremented by 1. The loop continues as long as the condition i <= 5
is true.
2. The while
Loop
The while
loop is used when you don't know the number of iterations in advance. It continues executing as long as a specified condition is true. Here's the basic structure:
while (condition) {
// Code to execute in each iteration
}
Here's an example that prints numbers from 1 to 5 using a while
loop:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
The while
loop checks the condition before each iteration. If the condition is false initially, the code inside the loop block will never run.
3. The do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the loop block will execute at least once. Here's the structure:
do {
// Code to execute in each iteration
} while (condition);
Here's an example that prints numbers from 1 to 5 using a do-while
loop:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
In this case, the code block is executed first, and then the condition is checked. If the condition is false initially, the loop block will still run once.
4. Loop Control Statements
JavaScript provides loop control statements to manage the flow of loops:
-
break
: Terminates the loop prematurely. -
continue
: Skips the current iteration and proceeds to the next one.
Here's an example that uses break
to exit a for
loop when a condition is met:
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Exit the loop when i is 5
}
console.log(i);
}
5. Nested Loops
You can also nest loops inside each other to create more complex iteration patterns. Here's an example with a nested for
loop:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
This code generates a table of values from 1 to 3 for both i
and j
.
Loops are incredibly powerful for automating repetitive tasks and processing collections of data in your JavaScript programs. They help you write efficient and maintainable code.
In the next section, we'll explore functions, which allow you to encapsulate and reuse blocks of code.