Unveiling JavaScript: While Loops

Unveiling JavaScript: While Loops

While Loops

Loops are a fundamental concept in programming, allowing you to execute a block of code repeatedly until a certain condition is met. JavaScript offers two primary looping constructs: while loops and do-while loops.

The while Loop: Entry-Controlled Repetition

The while loop is an entry-controlled loop, meaning it evaluates a condition before executing the loop body. The loop continues to iterate as long as the condition remains true.

Syntax:

while (condition) {
  // Code to be executed as long as the condition is true
}
  • condition: This is a JavaScript expression that evaluates to either true or false. The loop body executes only if the condition is true.

Example:

let count = 0;

while (count < 5) {
  console.log("Current count:", count);
  count++; // Increment count by 1
}

In this example, the loop iterates five times, printing the current count value in each iteration. The loop terminates when count becomes 5, as the condition count < 5 is no longer true.

The do-while Loop: Exit-Controlled Repetition

The do-while loop is an exit-controlled loop, meaning it executes the loop body at least once, regardless of the initial condition. The condition is then evaluated after each iteration to determine if the loop continues.

Syntax:

do {
  // Code to be executed at least once
} while (condition);

Example:

let guess = Math.floor(Math.random() * 10) + 1; // Random number between 1 and 10
let attempts = 0;

do {
  attempts++;
  console.log("Guess my number! (attempt:", attempts, ")");
  // Simulate user input (replace with actual user input logic)
  let userGuess = 5; // Replace with user's guess
} while (userGuess !== guess);

console.log("Congratulations! You guessed the number in", attempts, "attempts.");

This example simulates a guessing game. The loop executes at least once, displaying a prompt for the user's guess. The loop continues as long as the user's guess (simulated here) doesn't match the random number.

Choosing Between while and do-while Loops:

  • Use a while loop when you want to check the condition before executing the loop body, ensuring the loop might not run at all if the condition is initially false.

  • Use a do-while loop when you need the loop body to execute at least once, even if the condition is false initially.

By effectively using while and do-while loops, you can create repetitive tasks in your JavaScript programs, making your code more concise and efficient.