Open In App

How to Create a While Loop in JavaScript ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, you can create a while loop using the while keyword followed by a condition. The loop continues to execute as long as the specified condition evaluates to true.

Syntax:

while (condition) {
// Code to be executed while the condition is true
// The condition is checked before each iteration
}

Example: Here, the loop continues to execute as long as the counter is less than or equal to 5. The console.log(counter) statement prints the current value of the counter, and counter++ increments its value in each iteration.

Javascript




let counter = 1;
 
while (counter <= 5) {
    console.log(counter);
    counter++;
}


Output

1
2
3
4
5

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads