DEV Community

Cover image for For Loop vs While Loop in JavaScript 🔄
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

For Loop vs While Loop in JavaScript 🔄

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);
}
Enter fullscreen mode Exit fullscreen mode
Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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++;
}
Enter fullscreen mode Exit fullscreen mode
Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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 🚀

javascript #webdev #beginners #coding

Top comments (0)