Skip to content

do

In JavaScript, the do keyword starts a do...while loop, which runs its body once and then repeats it for as long as a condition checked after each pass is truthy. Because the test comes after the body, the body always runs at least once. The while keyword closes the statement and holds the condition, and a plain while loop checks its condition before the first pass instead.

Inside the body, break ends the loop and continue skips ahead to the condition check. The grammar ends the statement with a semicolon after the closing parenthesis, but automatic semicolon insertion adds one when it’s missing.

JavaScript do Keyword Syntax

A do...while loop runs a single statement or a block:

Language: JavaScript Syntax
do <statement> while (<condition>);

do {
  <statements>
} while (<condition>);

JavaScript do Keyword Examples

A do...while loop runs its body once before it checks the condition:

Language: JavaScript
> const taken = new Set(["user1", "user2"]);
undefined
> let count = 0;
undefined
> let userName;
undefined

> do {
…   count += 1;
…   userName = `user${count}`;
… } while (taken.has(userName));
'user3'
> userName
'user3'

The loop builds a candidate name before it checks anything, then repeats while the name is already taken.

The body runs once even when the condition is false from the start:

Language: JavaScript
> let attempts = 0;

undefined
> do {
…   attempts += 1;
… } while (attempts > 10);
1
> attempts
1

The condition attempts > 10 is already false after the first pass, so the loop stops with attempts at 1.

JavaScript do Keyword Use Cases

  • Running a step at least once before deciding whether to repeat it
  • Prompting for input until the answer is valid
  • Generating values until one passes a check, such as an unused name
  • Retrying an operation until it succeeds or reaches a limit

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 4, 2026