What is a For Loop?
A for loop is a control structure that repeats a block of code as long as a specified condition is true. It is particularly useful for executing repetitive tasks, such as iterating over arrays or performing calculations.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute in each iteration
}
Components of the Syntax:
- Initialization: Sets the loop counter’s starting value. (e.g., let i = 0)
- Condition: Specifies when the loop should stop. (e.g., i < 10)
- Increment/Decrement: Updates the loop counter after each iteration. (e.g., i++)
Example 1: Basic For Loop
for (let i = 0; i < 5; i++) {
console.log("Iteration number:", i);
}
// Output:
// Iteration number: 0
// Iteration number: 1
// Iteration number: 2
// Iteration number: 3
// Iteration number: 4
How Does the For Loop Work?
- The initialization (let i = 0) runs once at the start of the loop.
- The condition (i < 5) is checked before each iteration. If true, the loop runs; otherwise, it stops.
- After the loop body executes, the increment/decrement (i++) updates the loop counter.
- Steps 2 and 3 repeat until the condition becomes false.
Example 2: Iterating Over an Array
const fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output:
// Apple
// Banana
// Cherry
Example 3: Summing Numbers
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i; // Adds i to the sum in each iteration
}
console.log("Total sum:", sum);
// Output: Total sum: 15
Nested For Loops
You can use a for loop inside another for loop, called a nested loop.
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
// Output:
// i: 1, j: 1
// i: 1, j: 2
// i: 1, j: 3
// i: 2, j: 1
// ...
Skipping and Breaking Loop Iterations
Skip Iterations Using continue:
The continue statement skips the current iteration and moves to the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skips when i is 3
}
console.log(i);
}
// Output: 1, 2, 4, 5
Exit the Loop Using break:
The break statement stops the loop entirely.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Stops the loop when i is 3
}
console.log(i);
}
// Output: 1, 2
Example 4: Reversing a String
const str = "JavaScript";
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
console.log("Reversed string:", reversed);
// Output: Reversed string: tpircSavaJ
Advantages of the For Loop
- Control: You have complete control over the initialization, condition and updates.
- Versatility: Useful for iterating over arrays, strings or ranges.
- Efficiency: Executes tasks with minimal overhead.
Common Mistakes
Infinite Loop: Forgetting to update the loop counter causes infinite execution.
for (let i = 0; i < 5; ) {
console.log(i); // No increment: This will run forever!
}
Off-By-One Errors: Ensure loop conditions cover the intended range.
Accessing Undefined Indexes: Always validate array boundaries.
Best Practices
Use Meaningful Variable Names: Instead of i, use descriptive names like index or counter if the context requires.
for (let index = 0; index < items.length; index++) {
console.log(items[index]);
}
Avoid Nesting Too Many Loops: Use functions or other structures if loops become deeply nested.
Minimize Length Calculations in Loops: Store lengths in variables to improve performance.
const length = array.length;
for (let i = 0; i < length; i++) {
console.log(array[i]);
}