JavaScript for Loop
What is the for Loop?
The for loop is used to execute a block of code a specific number of times. It is commonly used for iterating over arrays or executing code repeatedly based on a condition.
Syntax
for (initialization; condition; increment) {
// Code to execute
}
- Initialization: Runs once before the loop starts, typically used to declare a loop counter.
- Condition: Evaluated before each iteration. If it evaluates to true, the loop continues; if false, the loop stops.
- Increment: Executes after each iteration, usually to update the loop counter.
Example: Basic for Loop
for (let i = 0; i < 5; i++) {
console.log('Iteration: ' + i);
}Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4Using the for Loop with Arrays
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}Output:
apple
banana
cherryExample: Summing Numbers
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log('Sum: ' + sum);Output:
Sum: 55Nested for Loops
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 2; j++) {
console.log('i: ' + i + ', j: ' + j);
}
}Output:
i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1When to Use the for Loop
The for loop is ideal for scenarios where you know the number of iterations in advance, such as processing arrays or executing a block of code a fixed number of times.
Conclusion
The for loop is a fundamental control structure in JavaScript that allows you to efficiently repeat code. Understanding how to use it effectively can enhance your coding skills.
×