How to Use While Loop in JavaScript: Syntax and Examples
In JavaScript, a
while loop repeatedly runs a block of code as long as the given condition is true. It checks the condition before each loop iteration, so if the condition is false initially, the code inside the loop won't run.Syntax
The while loop syntax consists of the keyword while, followed by a condition in parentheses, and a block of code inside curly braces. The loop runs the code block repeatedly as long as the condition is true.
- while: starts the loop
- (condition): a test that must be true to continue looping
- { ... }: the code to repeat
javascript
while (condition) { // code to run repeatedly }
Example
This example shows a while loop that counts from 1 to 5 and prints each number. The loop stops when the number becomes greater than 5.
javascript
let count = 1; while (count <= 5) { console.log(count); count++; }
Output
1
2
3
4
5
Common Pitfalls
One common mistake is forgetting to update the condition variable inside the loop, which causes an infinite loop. Another is using a condition that is always false, so the loop never runs.
Here is an example of an infinite loop and its fix:
javascript
// Wrong: infinite loop let i = 0; while (i < 3) { console.log(i); // missing i++ update } // Correct: update i to avoid infinite loop let j = 0; while (j < 3) { console.log(j); j++; }
Output
0
1
2
Quick Reference
Remember these tips when using while loops:
- Always ensure the condition will become false eventually to stop the loop.
- Update variables inside the loop to avoid infinite loops.
whileloops check the condition before running the code block.- Use
breakto exit the loop early if needed.
Key Takeaways
A while loop runs code repeatedly as long as its condition is true.
Always update the condition variable inside the loop to avoid infinite loops.
The condition is checked before each loop iteration, so the loop may not run at all if false initially.
Use break to exit a while loop early if needed.
While loops are useful when you don't know in advance how many times you need to repeat.