← Back to Roadmap

While Loop

Easy

In plain terms

while repeats a block while the condition is true. Check the condition before each iteration. Use when you do not know the number of iterations in advance.

What you need to know

  • Pre-condition check
  • Can run 0 or more times
  • do-while runs at least once

Try it yourself

Copy the code below and run it in your browser console or a code editor:

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

// Be careful: infinite loop if condition never false
// while (true) { }

// Do-while: runs at least once
let j = 0;
do {
  console.log(j);
  j++;
} while (j < 3);

Learn more

Dive deeper with these trusted resources: