In JavaScript, the while loop is used to execute a block of code as long as a specified condition is true. It's a pre-test loop, meaning the condition is evaluated before the execution of the block. If the condition evaluates to true, the block of code is executed. Here's the syntax of the while loop:
while (condition) {
// Code block to be executed
}
let count = 0;
while (count < 5) {
console.log("Count: " + count);
count++;
}
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
let userInput;
let sum = 0;
while (userInput !== 'exit') {
userInput = prompt("Enter a number (type 'exit' to stop):");
if (userInput !== 'exit' && !isNaN(userInput)) {
sum += parseFloat(userInput);
}
}
console.log("Sum of numbers entered: " + sum);
In this example, the loop continues prompting the user for numbers until they type exit. It then calculates the sum of the entered numbers.