While Loops: Basics to Advanced

In JavaScript, loops are used to execute a block of code repeatedly under certain conditions. The while and do-while loops are fundamental control structures that offer flexibility in how and when this repetition occurs.

The Structure of While Loops

A while loop will continue to execute a block of code as long as the specified condition evaluates to true. It’s crucial that the condition eventually becomes false; otherwise, you’ll find yourself stuck in an infinite loop.

I. Syntax

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

II. Example

let count = 0;

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

This loop will print “Count is: x” (where x ranges from 0 to 4) and then exit once count reaches 5, as the condition count < 5 becomes false.

The Structure of Do-While Loops

The do-while loop is similar to the while loop, with one key difference: the code block is executed once before the condition is tested. This guarantees that the code block is executed at least once.

I. Syntax

do {
  // code block to be executed
} while (condition);

II. Example

let result = '';

do {
  result += 'The number is ' + count;
  count++;
} while (count < 5);

console.log(result);

In this example, the do-while loop also appends a string to result with count ranging from 0 to 4, printing the message at least once even if the condition is initially false.

Practical Scenarios for While vs. For Loops

Choosing between while, do-while, and for loops often depends on the specific requirements of your task.

I. Use while When:

  • The number of iterations is not known before the loop starts.
  • You want the code to run only if a condition is met (since the condition is evaluated before the first iteration).

II. Use do-while When:

  • You need the loop to execute at least once, but the subsequent iterations depend on a condition being met.

III. Use for When:

  • You know the exact number of iterations in advance.
  • You need to initialize a counter, check a condition, and update the counter all in one line.

IV. Example: Choosing the Right Loop

Reading User Input Until They Type “Stop”

Using a while loop is more appropriate here because you don’t know how many inputs you’ll need to read.

let userInput;

while (userInput !== "stop") {
  userInput = prompt("Enter a value, or type 'stop' to end:");
}

Processing Items in an Array

A for loop is ideal for iterating over an array when you know its length.

const items = ['Apple', 'Banana', 'Cherry'];

for (let i = 0; i < items.length; i++) {
  console.log(items[i]);
}