How to Use For Loop in JavaScript: Syntax and Examples
In JavaScript, a
for loop repeats a block of code a set number of times using three parts: initialization, condition, and increment. You write it as for (initialization; condition; increment) { /* code */ } to run code repeatedly while the condition is true.Syntax
The for loop has three main parts inside parentheses, separated by semicolons:
- Initialization: Sets a starting point, usually a variable like
let i = 0. - Condition: A test that runs before each loop; if true, the loop continues.
- Increment: Changes the variable after each loop, often
i++to add 1.
The code inside curly braces { } runs each time the loop repeats.
javascript
for (let i = 0; i < 5; i++) { // code to repeat }
Example
This example prints numbers from 0 to 4 using a for loop. It shows how the loop runs 5 times, increasing i by 1 each time.
javascript
for (let i = 0; i < 5; i++) { console.log(i); }
Output
0
1
2
3
4
Common Pitfalls
Common mistakes with for loops include:
- Forgetting to update the loop variable, causing an infinite loop.
- Using the wrong condition, so the loop never runs or runs too many times.
- Declaring the loop variable outside the loop and accidentally reusing it elsewhere.
Always check your initialization, condition, and increment carefully.
javascript
/* Wrong: infinite loop because i is not incremented */ for (let i = 0; i < 5;) { console.log(i); i++; // Must increment inside if not in for statement } /* Right: increment inside for statement */ for (let i = 0; i < 5; i++) { console.log(i); }
Output
0
1
2
3
4
0
1
2
3
4
Quick Reference
Remember these tips for using for loops:
- Use
letto declare the loop variable for block scope. - The condition runs before each loop; if false, the loop stops.
- The increment runs after each loop iteration.
- You can use any expressions in initialization, condition, and increment.
Key Takeaways
A for loop repeats code using initialization, condition, and increment parts.
The loop runs while the condition is true and stops when it becomes false.
Always update the loop variable to avoid infinite loops.
Use let to declare the loop variable for proper scope.
Check your loop parts carefully to control how many times it runs.