Utilizor
Contact Us

JavaScript While Loop - Complete Guide with Examples

Learn JavaScript while loops with detailed examples. Master while, do-while loops, and loop control for efficient code iteration.

JavaScript While Loop

The while loop is another fundamental looping construct in JavaScript that executes a block of code as long as a specified condition remains true.

While Loop vs For Loop

While the for loop is typically used when you know how many times to loop, the while loop is ideal when the number of iterations is unknown and depends on a condition.

The While Loop Syntax

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

Types of While Loops

  • while - Checks condition before executing
  • do...while - Executes at least once, then checks condition

Warning: Always ensure your while loop has a way to become false, otherwise you'll create an infinite loop that can crash your browser!

Example

let count = 0;
while (count < 5) {
  console.log("Count is: " + count);
  count++;
}
// Output: Count is: 0, 1, 2, 3, 4