Menu Close

JavaScript while loop with examples

Codeamend

A while loop in JavaScript is a control structure that allows you to repeat a block of code while a certain condition is true. The syntax for a while loop is as follows:

while (condition) {
  // code to be executed while condition is true
} 

The condition is evaluated before each iteration of the loop, and if it is true, the code inside the loop is executed. The loop will continue to execute until the condition becomes false. Here are some examples of while loops in JavaScript and their use cases:

Example 1: Counting from 1 to 10

let i = 1;
while (i <= 10) {
  console.log(i);
  i++;
} 

In this example, the loop starts with the variable i set to 1. The loop will continue to execute as long as i is less than or equal to 10. Inside the loop, the current value of i is logged to the console, and then i is incremented by 1. The loop will repeat until i reaches 11.

Example 2: Getting user input until a valid value is entered

let userInput;
while (isNaN(userInput)) {
  userInput = prompt("Enter a number:");
}
console.log("You entered:", userInput); 

In this example, the loop prompts the user to enter a number until they enter a valid number (i.e. not NaN). The isNaN function is used to check if the user’s input is not a number. Once the user enters a valid number, the loop exits and the entered value is logged to the console.

Example 3: Processing an array

const numbers = [1, 2, 3, 4, 5];
let i = 0;
while (i < numbers.length) {
  console.log(numbers[i]);
  i++;
} 

In this example, the loop processes each element of the numbers array. The loop starts with i set to 0, and will continue to execute as long as i is less than the length of the numbers array. Inside the loop, the current element of the numbers array is logged to the console, and then i is incremented by 1. The loop will repeat until i is equal to the length of the numbers array.

While loops can be very useful in many situations where you need to repeat a block of code until a certain condition is met. However, it’s important to make sure that the condition will eventually become false, otherwise the loop will continue to run indefinitely, which is called an infinite loop.

Posted in JavaScript

You can also read...