While Loops

A while loop repeatedly executes a block of code as long as a specified condition remains true. It's one of the fundamental loop structures in JavaScript used for iteration.

Illustration of while_loops
Illustration of while_loops

💡 Basic Syntax

while (condition) {
  // code to run
}

The condition is evaluated before each iteration. If it is true, the loop body runs. If false, the loop stops.

📌 Deep Dive: Counting from 1 to 5

JAVASCRIPT
let counter = 1;
while (counter <= 5) {
  console.log(counter);
  counter++;
}
Output
1
2
3
4
5

Notice the importance of updating the counter variable inside the loop to avoid an infinite loop.

⚠️ Beware of Infinite Loops

If the loop condition never becomes false, the loop will run forever, potentially crashing your program. Always ensure the condition will eventually fail.

While Loop vs. For Loop
While LoopFor Loop
Condition checked before each iterationInitialization, condition, and increment in one line
Good when number of iterations is unknownIdeal when iterations count is known
Separate increment step required inside loopIncrement included in loop header

Typical use cases for while loops include:

  • Waiting for a condition to change dynamically
  • Reading data until no more is available
  • Repeating tasks until user input or external changes

📌 Deep Dive: Prompt Until Valid Input

JAVASCRIPT
let input;
while (!input) {
  input = prompt("Enter your name:");
}
console.log("Hello, " + input + "!");
Output
// Keeps prompting until a non-empty value is entered

💡 Important

Always ensure the loop’s condition will eventually evaluate to false to avoid freezing the program.