do...while

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

do...while 文は指定された文を、テスト条件が false に評価されるまで実行するループを作成します。条件は文を実行した後に評価されます。結果として、指定された文は少なくとも 1 回は実行されます。

試してみましょう

let result = "";
let i = 0;

do {
  i = i + 1;
  result = result + i;
} while (i < 5);

console.log(result);
// Expected output: "12345"

構文

js
do
  statement
while (condition);
statement

少なくとも 1 回は実行され、条件が真と評価されるたびに再実行される文。ループ内で複数の文を実行するには、それらの文をグループ化するためにブロック文 ({ /* ... */ }) を使ってください。

condition

ループを通過した後ごとに評価される式。もし conditiontrue に評価されるなら、statement は再度実行されます。conditionfalse に評価されるときは、制御が do...while に続く文へ渡ります。

メモ: break 文を使うと、condition が false と評価される前にループを停止することができます。

do...while の使用

次の例では、 do...while ループを少なくとも 1 回は実行し、 i が 5 より小さいという条件を満たさなくなるまで反復します。

js
let result = "";
let i = 0;
do {
  i += 1;
  result += `${i} `;
} while (i > 0 && i < 5);
// Despite i === 0 this will still loop as it starts off without the test

console.log(result);

条件として代入文を使用

場合によっては、条件として代入を使用することは意味があります。しかし、その場合、正しい方法と間違った方法があります。while のドキュメントでは、代入を条件として使用の節で、知っておくべき、そして従うべき一般的な良い実践例を示しています。

仕様書

Specification
ECMAScript® 2025 Language Specification
# sec-do-while-statement

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
do...while

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報