🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

While Loop

JavaScript While Loop

JavaScript While Loop

A while loop is another type of control flow statement in programming that repeatedly executes a block of code as long as a specified condition is true. The loop continues to execute until the condition becomes false. The basic syntax of a while loop is as follows:

while (condition) {
  // Code to be executed as long as the condition is true
}

Here's a simple example of a while loop that prints the numbers 1 to 5:

let i = 1;

while (i <= 5) {
  console.log(i);
  i++;
}

In this example:

  • i is initialized to 1 before the while loop.
  • The condition i <= 5 is checked before each iteration. If it evaluates to true, the code inside the loop is executed.
  • i++ increments the value of i after each iteration.

The loop will print the numbers 1 to 5, similar to the for loop example.

Examples:

Iterating Over an Array:

const colors = ["red", "green", "blue"];
let index = 0;

while (index < colors.length) {
  console.log(colors[index]);
  index++;
}

Infinite Loop (Be Careful!):

let counter = 0;

while (true) {
  console.log(counter);
  counter++;

  if (counter === 5) {
    break; // Ensure the loop doesn't run indefinitely
  }
}

Using continue and break:

let num = 1;

while (num <= 10) {
  if (num % 2 === 0) {
    num++;
    continue; // Skip even numbers
  }

  console.log(num);

  if (num === 7) {
    break; // Exit the loop when num is 7
  }

  num++;
}

while loops are useful when the number of iterations is not known in advance or when the loop should continue until a specific condition is met. It's important to ensure that the condition eventually becomes false to avoid infinite loops.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.