For Loops
JavaScript For Loop
A for
loop is a control flow statement in programming that allows you to repeatedly execute a block of code as long as a specified condition is true. The syntax of a for
loop consists of three parts: initialization, condition, and iteration. Here's the basic structure:
for (initialization; condition; iteration) {
// Code to be executed in each iteration
}
- Initialization: Typically, this part is used to initialize a counter variable. It runs once at the beginning of the loop.
- Condition: The loop continues as long as this condition is true. If the condition evaluates to false, the loop exits.
- Iteration: This part is executed after each iteration of the loop. It is commonly used to update the counter variable.
Example:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
In this example:
let i = 1
initializes a counter variablei
to 1.i <= 5
is the condition that specifies when the loop should continue.i++
increments the counter variable by 1 after each iteration.
The loop will execute five times, printing the numbers 1 to 5.
Examples:
Iterating Over an Array:
const fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Nested Loops:
for (let i = 1; i <= 3; i++) {
for (let j = 1; i <= 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
Skipping Iteration (using continue
):
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip iteration when i is 3
}
console.log(i);
}
Breaking Out of a Loop (using break
):
for (let i = 1; i <= 5; i++) {
if (i === 4) {
break; // Exit the loop when i is 4
}
console.log(i);
}
for
loops are powerful constructs for iterating over sequences, such as arrays, and performing repetitive tasks. They are widely used in programming to automate processes that involve repetitive actions.