JavaScript - While & Do...While

Overview

Estimated time: 15–25 minutes

while repeats while a condition is true; do...while runs the body at least once.

Learning Objectives

  • Choose between while and do...while.
  • Write loops with proper termination.

Prerequisites

Examples

let n = 0;
while (n < 3) { n++; }

do {
  n--;
} while (n > 0);

Common Pitfalls

  • Forgetting to update the loop variable leads to infinite loops.