JavaScript : While Loop

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:

Syntax:


while (condition) {
  // Code block to be executed
}

 

  • condition : An expression that is evaluated before each iteration. If the condition evaluates to true , the loop continues; if false, the loop terminates.

Example:


let count = 0;

while (count < 5) {
  console.log("Count: " + count);
  count++;
}

 

Output:


Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

 

Notes:

 

  • Make sure to include an update statement inside the loop to avoid infinite loops. Without an update statement, the loop will continue indefinitely.
  • If the condition evaluates to false initially, the code inside the loop will not execute at all.
  • You can use the while loop when you don't know in advance how many times the loop needs to be executed, and the number of iterations depends on a condition.

Example with User Input:


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.