while Loop in JavaScript

After for loop in JavaScript, the next very common loop in JavaScript is while loop. It is a control flow statement that allows repeated execution of the code based on the given condition. It checks a certain condition to be true and till then repeats the block of code.

The syntax of while loop in JavaScript:

while(condition){
    //code
}

where the condition is evaluated before each iteration of the loop. If the condition is true, the code within the loop is executed. Once the code within the loop has finished executed, the condition is evaluated again, and the process continues until the condition is false.

Example 1:

let i=0;
while (i<5){
    console.log(i);
    i++;
}
Output 1:

0

1

2

3

4

The code gives the above-mentioned output until i value is less than 5 and terminates as soon as the condition fails.

Example 2:

let password = "secret";
let input;
while (input !== password) {
    input = prompt("Enter the password:");
}
console.log("Password accepted!");
Output 2:

The above given code gives "Password accepted!" when it matches with the input, and if not, it again asks you to enter the password.

Conclusion

In this module, we have discussed the while loop in JavaScript. We have also gone through some of the examples of the while loop which describes its functioning. While loop in JavaScript is used typically when you don't know in advance how many times a block of code has to be repeat. Thus, it is a useful tool which allows you to perform an operation multiple times while a certain condition is true.


Learn via Video Course

Javascript(English) Logo

Javascript(English)

72966

3 hrs