How to execute a while loop in JavaScript

A while loop consists of a condition(s) and as long as that condition(s) is true, the set of statements inside the while block is executed repeatedly. A while loop is the only necessary repetition construct. The for-loop, can be duplicated using a while loop with far more control.

while-loop
while-loop

Syntax

The general syntax of a while loop in JavaScript is given below. Here, condition is a statement. It can consist of multiple sub-statements i.e. there can be multiple conditions.

For as long as condition evaluates to true, the code written inside the while block keeps on executing. As soon as condition evaluates to false, the loop breaks.

while(condition){
// code statements to run repeatedly
}

Infinite loop

For the condition to eventually evaluate to false, it is essential that the control variables being used inside the conditional statement are updated properly.

An improper update may result in an infinite loop; the program is stuck inside the while loop, having found no terminating condition and continues executing the statements within the loop.

Example

Take a look at the following example. The while loop runs as long as the condition, y <= 10, is being met. The statements on line 6-8 execute if the expression inside the parenthesis evaluates to true.

When the expression evaluates to false the program comes out of the loop and prints the final values of x and y.

svg viewer
var x = 4, y = 0, i = 1;
// the while loop will run till y<=10
// the loop will iterate 3 times
while (y <= 10){
y += x
x += 1
console.log("Iteration: ", i++, "; x:", x, "; y:", y);
}
console.log("the value of x is:", x);
console.log("the value of y is:", y);
Copyright ©2024 Educative, Inc. All rights reserved