When learning JavaScript, loops are essential because they help you repeat tasks efficiently. One of the most important loops is the while loop. It is simple, powerful, and widely used in real-world programming.
What is a While Loop in JavaScript?
A while loop is used when you want to repeat a block of code as long as a condition is true.
The loop keeps running until the condition becomes false.
For example:
-
Keep asking for a password until the correct one is entered
-
Run a game until the player loses
-
Read data until there is no more data
How it works:
-
The condition is checked first
-
If the condition is true, the code inside the loop runs
-
After execution, the condition is checked again
-
This continues until the condition becomes false
Explanation:
-
i starts from 1
-
The loop runs while
i <= 5 -
i++ increases the value each time
2
3
4
5
Output:
Total: 15
Common Mistakes to Avoid
Infinite Loop (Forgetting to update value)
Always ensure the condition eventually becomes false.
When Should You Use While Loop in JavaScript?
Use a while loop when:
-
You do not know how many times the loop will run
-
The loop depends on user input
-
The loop depends on dynamic conditions
-
You are working with validation logic