JavaScript while

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

while checks a condition first, then runs the body. It keeps going until the condition becomes falsy. Make sure something inside the loop moves toward stopping.

JavaScript Syntax

JavaScript
let n = 3;
while (n > 0) {
  console.log(n);
  n--;
}
Try it Editor

How It Works

  1. Check first. n > 0 is true.
  2. Update n. Decrement each pass so the loop can end.

Examples

Example 1 — Body may never run

If the condition starts false, skip the body.

JavaScript
let n = 0;
while (n > 0) console.log("hi");
console.log("done");
Try it Editor

How It Works

  1. Condition is false immediately.
  2. Only done prints.

Example 2 — Unknown count

Keep going until a flag changes.

JavaScript
let left = 2;
while (left) {
  console.log("tick");
  left--;
}
Try it Editor

How It Works

  1. left is truthy while 2 and 1.
  2. Becomes 0 and stops.

Example 3 — Need at least one pass?

Use do...while instead.

JavaScript
console.log("see do...while page");
Try it Editor

How It Works

  1. do...while runs the body before the first check.

Frequently Asked Questions

A loop whose condition never becomes falsy. Always update a counter or flag.
for packs init/check/step together. while shines when the stop condition is not a simple counter.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful