javascript while loop

JavaScript: while Loop

The while loop in JavaScript is used to repeat a block of code as long as a condition is true. It’s perfect for situations where you don’t know exactly how many times you’ll need to run the code but want to keep going as long as something specific is happening.

A while loop checks a condition before running the code inside it. If the condition is true, it keeps running the code. Once the condition becomes false, the loop stops.

The while loop is great when you want to repeat something until a certain condition is met, like counting numbers or waiting for a user to enter information.

In this article, we’ll learn how to:

  • Use the basic syntax of the while loop.
  • Repeat tasks until a condition is met.
  • Skip or stop the loop using continue and break.

By the end, you’ll be ready to use the while loop to repeat tasks in your JavaScript code!

Basic Syntax of the while Loop

The while loop in JavaScript is a simple and effective way to repeat a block of code as long as a condition is true. Here’s how it looks:

while (condition) {
  // Code to execute
}

Condition is the test that the loop checks before each iteration. It’s an expression that must evaluate to true for the loop to keep running. If it evaluates to false, the loop will stop.

Code Block inside the curly braces {} is the block that will be executed every time the condition is true. After the code runs, the condition is checked again to see if the loop should continue.

Example: Counting from 1 to 5

Here’s an example where we print the numbers from 1 to 5 using a while loop:

let i = 1;

while (i <= 5) {

  console.log(i);
  i++; // Increment i by 1 after each loop

}

In this example:

  1. We start by setting i to 1.
  2. The loop checks if i is less than or equal to 5.
  3. If i is less than or equal to 5, it prints the value of i, then increases i by 1.
  4. This repeats until i becomes greater than 5, and the loop stops.

The loop continues to run as long as the condition (i <= 5) is true. Once i is 6, the condition becomes false, and the loop stops.

Infinite while Loop

A while loop runs as long as its condition evaluates to true. But what happens if the condition is always true? You end up with an infinite loop, meaning the code will keep running forever unless manually stopped. This is useful in some situations, like waiting for user input, but in most cases, you’ll want to avoid it.

Here’s an example of an Infinite Loop:

while (true) {

  console.log("This will run forever!");
  break;  // Adding a break to stop the loop for this demo

}

Condition is always true, so the loop will continue infinitely. It will continuously print "This will run forever!" to the console. We use break here to stop the loop after just one iteration for demonstration purposes. Without break, the loop would run endlessly, which is generally not desired in real-world code.

Real-World Scenario

Infinite loops are often used in situations where you need to keep checking something continuously, like a server that listens for requests. But you must always have a way to exit the loop when needed (like a break condition or external signal).

Without the break, the loop would never stop, so always be careful when using a condition like while (true).

Using while with Arrays (Accessing Elements)

The while loop can be a great way to loop through the elements of an array. By manually managing the index, you can access and process each element in the array.

Example: Loop Through an Array

const fruits = ["apple", "banana", "cherry"];

let i = 0;

while (i < fruits.length) {

  console.log(fruits[i]);
  i++;

}
// Output: apple, banana, cherry

fruits contains three elements: "apple", "banana", and "cherry". The loop uses the i variable to track the index, starting at 0. The loop continues as long as i is less than the length of the array (fruits.length), ensuring all elements are accessed. Inside the loop, fruits[i] accesses the element at the current index, printing each fruit. After each iteration, i is increased by 1 to move to the next element in the array.

This example demonstrates how to manually loop through an array using a while loop. It works well, especially when you need to process each element step by step.

Using while with Strings

You can also use the while loop to iterate through each character in a string. Just like with arrays, you can access individual characters using their index positions.

Example: Loop Through Each Character in a String

const word = "hello";

let i = 0;

while (i < word.length) {

  console.log(word[i]);
  i++;

}
// Output: h, e, l, l, o

word is the string "hello". The loop uses i to keep track of the index, starting at 0 for the first character. The loop continues as long as i is less than the length of the string (word.length), so it iterates over each character in the string. Inside the loop, word[i] accesses the character at the current index and logs it to the console. After each iteration, i is incremented by 1 to move to the next character in the string.

This method works similarly to looping through an array, except it accesses each character in a string. It’s a great way to process strings character by character.

Using while for Conditional Repeating Tasks

The while loop is great for situations where you need to repeat a task until a certain condition is met. This is especially useful for handling user input or performing actions until specific criteria are satisfied.

Example: Looping Based on User Input

let userInput = "";

while (userInput !== "exit") {
  userInput = prompt("Type 'exit' to stop");
  console.log("You typed: " + userInput);
}

We start by initializing userInput as an empty string. The while loop continues as long as userInput is not equal to "exit". Once the user types "exit", the loop stops. Inside the loop, the prompt() function asks the user to type something. The value the user types is then stored in userInput. After the user enters something, we log the message "You typed: " + userInput to the console, showing what they entered. The loop will keep repeating until the user types "exit", which then ends the loop.

This demonstrates how to use a while loop to repeatedly ask for input until the user provides a specific response, such as typing "exit". You can apply this technique for any task that requires repeating actions based on a condition.

Skipping Iterations with continue in while Loop

The continue statement in a while loop allows you to skip the current iteration and move to the next one. This is helpful when you want to avoid executing certain code under specific conditions, without stopping the entire loop.

Example: Skip Even Numbers Using continue

let i = 0;

while (i < 10) {

  i++;

  if (i % 2 === 0) continue;  // Skip even numbers

  console.log(i);  // Output: 1, 3, 5, 7, 9

}

Inside the loop, we check if i is even using the condition i % 2 === 0. If the number is even, the continue statement is triggered, which skips the console.log(i) line and moves directly to the next iteration of the loop. For odd numbers, the console.log(i) line is executed, and the odd number is printed to the console. The loop increments i on each iteration, ensuring it eventually reaches 10 and exits.

In this example, the while loop iterates through numbers from 1 to 9, but only prints the odd ones because the even numbers are skipped using continue.

Breaking Out of a while Loop Early with break

Sometimes, you may want to stop a while loop before it finishes all its iterations. The break statement allows you to exit the loop as soon as a specific condition is met.

Example: Exit the Loop Early When a Condition is Met

let i = 1;

while (i <= 10) {

  if (i === 5) break;  // Stop the loop when i reaches 5

  console.log(i);

  i++;

}
// Output: 1, 2, 3, 4

The loop starts with i = 1 and will run while i is less than or equal to 10. Inside the loop, we check if i is equal to 5. If this condition is true, we use the break statement to exit the loop immediately. When i reaches 5, the break statement is triggered, and the loop stops. As a result, the loop only prints the numbers 1 through 4, skipping the print for 5 and the rest of the numbers. The loop continues to increment i on each iteration until the break condition is met.

In this example, the loop doesn’t run until the condition i <= 10 is false. Instead, it stops early when i equals 5, thanks to the break statement.

Using while with Custom Conditions

You can make a while loop more flexible by using dynamic conditions. This means you can adjust the loop’s behavior (such as incrementing a variable or checking a condition) while the loop is running.

Example: Loop Until a Dynamic Condition is Met

let i = 0;

while (i < 20) {

  console.log(i);
  i += 2;  // Increment by 2 each time

}
// Output: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18

The loop starts with i = 0. The loop runs as long as i is less than 20, but each time through the loop, i is incremented by 2 (i += 2). The loop prints even numbers from 0 to 18. This demonstrates how you can customize the loop’s behavior and control the flow of iterations based on a dynamic condition, rather than just a simple static check. You could change the increment or the condition within the loop to make it behave differently based on user input or other variables.

This example shows how while loops can be adapted to more complex conditions, making them flexible and powerful tools for repeating tasks in JavaScript.

while Loop vs do-while Loop

While both while and do-while loops are used to repeat a block of code as long as a condition is true, they have a key difference in when the condition is checked.

The Difference

while Loop: Checks the condition before running the code. If the condition is false initially, the code inside the loop will never run.

do-while Loop: Checks the condition after running the code. This means that the code inside the loop will always run at least once, even if the condition is false at the start.

Example of do-while Loop

let i = 1;

do {

  console.log(i);
  i++;

} while (i <= 5);
// Output: 1, 2, 3, 4, 5

Even though i starts as 1 and the condition i <= 5 is checked at the end of each iteration, the loop runs once before checking the condition. The numbers 1, 2, 3, 4, 5 are printed to the console because the loop ensures the code inside the block runs first.

The main advantage of the do-while loop is that you are guaranteed to execute the code inside the loop at least once, even if the condition is false initially.

When to Use Each:

  • Use a while loop when you want to check the condition before running the loop.
  • Use a do-while loop when you need the code inside the loop to run at least once, regardless of the condition.

Conclusion

The while loop in JavaScript is a powerful and flexible tool that allows you to repeat a block of code as long as a specific condition remains true. It’s perfect for scenarios where you don’t know how many times the loop should run in advance, but instead, the condition determines the loop’s continuation.

  • The while loop runs as long as the condition is true, making it ideal for dynamic tasks.
  • You can use the while loop with arrays, strings, numbers, and custom conditions to solve a wide range of problems.
  • Don’t forget that an infinite loop can occur if the condition is always true, so always ensure the condition eventually becomes false or use break to control it.

The while loop is a staple in JavaScript, offering flexibility for various scenarios. Whether you’re iterating through data or handling user input, it’s a great choice for repeating tasks. Don’t hesitate to experiment with different conditions and combine it with other loop structures like do-while for even more control over your program flow.

Scroll to Top