While loop

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

while and do...while

JS · Control Flow
Syntax
while (condition) { ... }
do { ... } while (condition);
Example
// Retry until success (with limit)
let attempts = 0;
let success = false;
while (!success && attempts < 5) {
  attempts++;
  success = Math.random() > 0.7;
}
console.log(`Succeeded after ${attempts} attempt(s): ${success}`);

// do...while always runs at least once
let input;
do {
  input = prompt("Enter a number > 10:");
} while (Number(input) <= 10);

Note do...while guarantees at least one iteration. Useful for retry logic and input validation loops.

PYPython

while Loops

PY · Control Flow
Syntax
while condition:
    ...
Example
attempts = 0
max_attempts = 3

while attempts < max_attempts:
    attempts += 1
    print(f"Try {attempts}")

print("Done")
Output
Try 1
Try 2
Try 3
Done

Note Make sure the condition eventually becomes False; otherwise you get an infinite loop. Use Ctrl+C to interrupt a runaway loop.

Frequently asked questions

How does JavaScript handle while loop?
This task is covered in 2 stacks on this page: JavaScript, Python. The "while and do...while" snippet in JavaScript uses `while (condition) { ... }`.
Which code does the JavaScript example use?
The "while and do...while" snippet uses `while (condition) { ... }`, from the Control Flow section of the JavaScript cheat sheet.
Which stacks cover "while loop" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "while and do...while": do...while guarantees at least one iteration. Useful for retry logic and input validation loops.