JavaScript For Loop – Looping Through Code
The for loop in JavaScript is used to repeat a block of code a certain number of times.
1. Syntax of for Loop:
for (initialization; condition; increment/decrement) {
// Code to be executed in each iteration
}
Explanation:
- Initialization: This part runs once before the loop starts. It is typically used to initialize a counter variable.
- Condition: This expression is evaluated before each loop iteration. The loop runs as long as this condition evaluates to
true. - Increment/Decrement: This expression updates the loop counter after each iteration.
2. Example of a Simple for Loop:
for (let i = 0; i < 5; i++) {
console.log("Iteration number: " + i);
}
Explanation:
- The loop starts with
i = 0. - The loop runs as long as
i < 5. - After each iteration,
iis incremented by 1.
Output:
Iteration number: 0 Iteration number: 1 Iteration number: 2 Iteration number: 3 Iteration number: 4
3. Using for Loop to Iterate Over an Array:
let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Explanation:
- The loop iterates through the
fruitsarray. fruits.lengthgives the number of elements in the array, ensuring the loop iterates over each element.
Output:
Apple Banana Cherry
4. Using for Loop with Decrement:
for (let i = 5; i > 0; i--) {
console.log("Countdown: " + i);
}
xplanation:
- The loop starts with
i = 5and decrementsiby 1 in each iteration untili > 0isfalse.
Output:
Countdown: 5 Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1
5. Nested for Loops:
A nested for loop is a loop inside another loop. It is often used for working with multi-dimensional arrays or grids.
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
Explanation:
- The outer loop runs 3 times (
ifrom 1 to 3). - For each iteration of the outer loop, the inner loop runs 3 times (
jfrom 1 to 3).
Output:
i: 1, j: 1 i: 1, j: 2 i: 1, j: 3 i: 2, j: 1 i: 2, j: 2 i: 2, j: 3 i: 3, j: 1 i: 3, j: 2 i: 3, j: 3
6. Skipping and Breaking Loops:
Using break Statement:
The break statement exits the loop immediately.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
Output:
0 1 2 3 4
Using continue Statement:
The continue statement skips the current iteration and proceeds with the next one.
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
console.log(i);
}
Output:
0 1 2 3 4 6 7 8 9
Conclusion:
- The
forloop is a powerful and versatile way to iterate over items or perform repeated tasks. - It offers full control over the iteration process through initialization, condition checking, and increment/decrement expressions.
- Using break and continue helps manage flow control within loops effectively.