If you are learning JavaScript, one of the most important concepts you must understand is the for loop. Loops help you repeat tasks efficiently and write cleaner, shorter code. In this guide, you will learn everything about the for loop in JavaScript with easy explanations and practical examples.
What is a For Loop in JavaScript?
A for loop is used when you want to run a block of code multiple times. Instead of writing the same code again and again, you can use a loop to automate repetition.
For example, if you want to print numbers from 1 to 10, you can use a for loop instead of writing ten console.log() statements.
Syntax of For Loop in JavaScript
Each part has a specific role:
Initialization → Starts the loop (e.g., let i=1)
-
Condition → Loop runs while this is true
-
Update → Changes the value after every iteration (e.g., i++)
Explanation
-
The loop starts at 1
-
Runs until 5
-
Increases by 1 each time
Output:
1 2 3 4 5
This is one of the most common for loop examples in JavaScript.
Example 2: Print Even Numbers Using For Loop
Output:
2 4 6 8 10
This example shows how you can control the loop step using i+=2
Example 3: Loop Through an Array in JavaScript
Explanation:
-
Arrays start from index 0
-
languages.length gives total items
-
The loop prints each element
Common Mistakes Beginners Make
1. Infinite Loop
This never stops because the condition always stays true.
2. Forgetting to Update Counter
Always remember to update the counter i++
When Should You Use a For Loop?
Use a for loop in JavaScript when:
-
You know how many times the loop should run
-
You are working with arrays
-
You need a counter
-
You want better control over iterations