0
0
Javascriptprogramming~5 mins

While loop in Javascript

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of actions as long as a condition is true. It saves time by avoiding writing the same code again and again.

When you want to keep asking a user for input until they give a valid answer.
When you need to count or process items until a certain limit is reached.
When you want to repeat a task but don't know in advance how many times it will run.
When you want to keep checking if something has happened and stop once it does.
Syntax
Javascript
while (condition) {
  // code to run repeatedly
}

The condition is checked before each loop. If it is true, the code inside runs.

If the condition is false at the start, the code inside will not run at all.

Examples
This prints numbers 0, 1, and 2. The loop stops when count reaches 3.
Javascript
let count = 0;
while (count < 3) {
  console.log(count);
  count++;
}
This keeps asking the user to type 'yes' to stop the loop.
Javascript
let input = '';
while (input !== 'yes') {
  input = prompt('Type yes to stop');
}
Sample Program

This program prints numbers from 1 to 5 using a while loop.

Javascript
let number = 1;
while (number <= 5) {
  console.log(`Number is ${number}`);
  number++;
}
OutputSuccess
Important Notes

Make sure the condition will eventually become false, or the loop will run forever.

You can use break inside the loop to stop it early if needed.

Summary

A while loop repeats code while a condition is true.

It checks the condition before running the code each time.

Use it when you don't know how many times you need to repeat something.