JavaScript For Loop
A for loop is used to execute a block of code repeatedly for a specific number of times. Loops help reduce duplicate code and make programs more efficient.
Instead of writing the same statement multiple times manually, we can use loops to automate repetitive tasks.
Why For Loop is Important?
- Reduces duplicate code
- Saves development time
- Automates repetitive tasks
- Makes programs cleaner
- Improves code efficiency
Syntax of For Loop
for(initialization; condition; update){
// code block
}
Explanation of Syntax
- Initialization runs only once at the beginning.
- Condition checks whether the loop should continue.
- Update changes the loop variable after every iteration.
- The loop stops when the condition becomes false.
Basic For Loop Example
The following example prints numbers from 1 to 5.
for(let i = 1; i <= 5; i++){
console.log(i);
}
Output
1 2 3 4 5
Detailed Explanation
- let i = 1 initializes the loop variable.
- i <= 5 checks the condition.
- i++ increases the value by 1.
- The loop repeats until the condition becomes false.
Reverse For Loop
A for loop can also run in reverse order.
for(let i = 5; i >= 1; i--){
console.log(i);
}
Output
5 4 3 2 1
Explanation
- The loop starts from 5.
- i-- decreases the value after every iteration.
- The loop stops when i becomes less than 1.
Printing Even Numbers
Loops are commonly used for calculations and patterns.
for(let i = 2; i <= 10; i += 2){
console.log(i);
}
Output
2 4 6 8 10
Explanation
- The loop starts from 2.
- i += 2 increases value by 2.
- Only even numbers are printed.
Calculating Sum Using Loop
Loops can perform repeated calculations.
let sum = 0;
for(let i = 1; i <= 5; i++){
sum = sum + i;
}
console.log(sum);
Output
15
Detailed Explanation
- sum initially stores 0.
- The loop adds numbers from 1 to 5.
- Final result becomes 15.
Nested For Loop
A loop inside another loop is called a nested loop.
for(let i = 1; i <= 3; i++){
for(let j = 1; j <= 2; j++){
console.log(i, j);
}
}
Output
1 1 1 2 2 1 2 2 3 1 3 2
Explanation
- The outer loop controls rows.
- The inner loop runs completely for each outer iteration.
- Nested loops are useful for tables and patterns.
Looping Through Arrays
For loops are commonly used with arrays.
let colors = ["Red", "Blue", "Green"];
for(let i = 0; i < colors.length; i++){
console.log(colors[i]);
}
Output
Red Blue Green
Explanation
- colors.length returns total array items.
- colors[i] accesses array elements.
- The loop prints every value one by one.
Infinite Loop
If the condition never becomes false, the loop runs forever.
for(let i = 1; i > 0; i++){
console.log(i);
}
Explanation
- The condition always remains true.
- The loop never stops.
- Infinite loops should be avoided.
Using break Statement
The break statement stops the loop immediately.
for(let i = 1; i <= 10; i++){
if(i == 5){
break;
}
console.log(i);
}
Output
1 2 3 4
Explanation
- The loop stops when i becomes 5.
- break immediately terminates execution.
Using continue Statement
The continue statement skips the current iteration.
for(let i = 1; i <= 5; i++){
if(i == 3){
continue;
}
console.log(i);
}
Output
1 2 4 5
Explanation
- The loop skips number 3.
- continue moves directly to the next iteration.
Complete Real Life Example
The following example shows a simple product list generator using JavaScript for loop.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript For Loop Example</title>
</head>
<body>
<h2>Product List</h2>
<button onclick="showProducts()">
Show Products
</button>
<ul id="output"></ul>
<script>
function showProducts(){
let products = [
"Laptop",
"Mobile",
"Headphones",
"Keyboard",
"Mouse"
];
let result = "";
for(let i = 0; i < products.length; i++){
result += "<li>" +
products[i] +
"</li>";
}
document.getElementById("output").innerHTML =
result;
}
</script>
</body>
</html>
Output
Product List • Laptop • Mobile • Headphones • Keyboard • Mouse
Detailed Explanation of Example
- The array stores product names.
- The loop runs through every product.
- Each product is converted into a list item.
- result += appends new HTML content.
- innerHTML displays the generated list on the webpage.
- Loops help generate repeated content dynamically.
Common Mistakes
- Forgetting loop update statements.
- Writing incorrect loop conditions.
- Creating infinite loops accidentally.
- Using wrong array indexes.
Best Practices
- Keep loop conditions simple.
- Use meaningful variable names.
- Avoid unnecessary nested loops.
- Prevent infinite loops.
- Use loops only when repetition is required.
Important Notes
- for loops repeat code automatically.
- Loops stop when conditions become false.
- break stops loop execution.
- continue skips current iteration.
- Loops are commonly used with arrays.
Summary
- for loops execute code repeatedly.
- Initialization runs only once.
- Conditions control loop execution.
- Update statements change loop values.
- Nested loops contain loops inside loops.
- break stops loops immediately.
- continue skips iterations.
- Loops are essential for dynamic programming.