Edit Template
Edit Template

While Loop

In JavaScript, a while loop lets you keep running a block of code as long as a condition remains true. It’s like saying, “keep doing this until something changes.”

This is very useful when you don’t know in advance how many times the loop needs to run.

Syntax

				
					while (condition) {
  // run this code
}

				
			

Before each run, the condition is checked. If it’s true, the loop runs. If it’s false, the loop stops right there.

Example 1: Count from 1 to 5
				
					let count = 1;

while (count <= 5) {
  console.log("Number:", count);
  count++; // important to avoid infinite loop
}

				
			
Output:
				
					Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

				
			

Here, we keep printing numbers until the count reaches 6. Without count++, the loop would keep running forever!

Example 2: Keep Asking Until Valid Input

Sometimes we need to ask users to give a correct input — and we don’t know how long it’ll take.

				
					let answer = "";

while (answer !== "yes" && answer !== "no") {
  answer = prompt("Do you agree? Type 'yes' or 'no'");
}


				
			

This loop will keep asking until the user types either “yes” or “no”. Super handy for form validations or menus.

Infinite Loops

If the condition never becomes false, the loop will run forever and can crash your browser.

For example:

				
					let x = 1;

while (x > 0) {
  console.log("Still running...");
  // Oops! x is never updated
}

				
			

Always make sure something inside the loop changes the condition eventually.

When to Use while

  • You want something to repeat, but you’re not sure how many times

  • You need to wait for a user action or valid input

  • A for loop doesn’t quite fit your scenario

Scroll to Top