When I started learning JavaScript, I was confused about when to use a for loop and when to use a while loop.
Both are used to repeat a block of code, but they are useful in different situations.
What is a For Loop?
A for loop is useful when we know how many times we want to repeat something.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
Here, the loop runs 5 times.
What is a While Loop?
A while loop is useful when we want to repeat something until a condition becomes false.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Output:
1
2
3
4
5
Easy Example 💡
Imagine you want to print numbers from 1 to 10.
Use a for loop:
for (let i = 1; i <= 10; i++) {
console.log(i);
}
But if you want to keep running something while a user has not entered the correct value, a while loop can be more suitable.
My Simple Rule
👉 Know the number of repetitions? → Use for
👉 Don't know how many repetitions? → Consider while
Conclusion
Both loops are important in JavaScript. As a beginner, don't worry too much about choosing the "perfect" loop. Practice both and understand how the condition works.
Learn → Practice → Build 🚀
Top comments (0)