A JavaScript while loop executes a block of code until a condition evaluates to true. Where the condition is evaluated before executing the statement.
while (condition) {
// code block to be executed
}
Example While loop JavaScript
Simple example code executes a statement or code block repeatedly as long as an expression is true using JavaScript while loop.
Run the loop until i
is less than 5.
<!DOCTYPE html>
<html>
<head>
<script>
i = 0;
while (i < 5) {
console.log("The number is " + i);
i++;
}
</script>
</head>
<body>
</body>
</html>
Output:
![While loop JavaScript](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2022/01/While-loop-JavaScript.jpg?resize=217%2C137&ssl=1)
Print Array elements using a while loop. The code in the loop will run, over and over again, as long as a variable (i) is equal to the length of the Array.
<script>
const cars = ["BMW", "Volvo", "Saab", "Ford"];
var l = cars.length;
var i = 0;
while (i != l) {
console.log(cars[i]);
i++;
}
</script>
Output:
![Print Array elements using while loop](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2022/01/Print-Array-elements-using-while-loop.jpg?resize=176%2C147&ssl=1)
Do comment if you have any doubts or suggestions on this JS Loop topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version