do while loop help

function cpuChoice() {
let randomNumber
do {
randomNumber = Math.floor(Math.random() * tilesArr.length);
tiles[randomNumber].classList.add("green-mark", "marked")

} while (tiles[randomNumber].classList.contains("marked") == false);
}
function cpuChoice() {
let randomNumber
do {
randomNumber = Math.floor(Math.random() * tilesArr.length);
tiles[randomNumber].classList.add("green-mark", "marked")

} while (tiles[randomNumber].classList.contains("marked") == false);
}
will the condition inside the while (), make the statement inside do {} run as long as the while() condition is true
5 Replies
Jochem
Jochemβ€’2mo ago
do {} while() runs once, checks the condition for the while, and reruns on true it then rechecks the while condition, and either reruns or continues to the next line of code under the do-while
bfmv
bfmvOPβ€’2mo ago
it will run atleast once, regardless if the condition inside the while () is true or false?
Jochem
Jochemβ€’2mo ago
yes if you want something that runs 0-N times, you use while () {}, if you want something that runs 1-N times, you use do {} while () the most common thing I use do-whiles for is things that need retrying if they fail, or operations that need to be repeated until they fail. A common one is fetching pages from an API that gives you a "next" pointer, or processing database rows from a query one by one you can also (ab)use it for running API requests that may fail and require re-authorization or a token refresh, though there's for sure better ways to handle that
bfmv
bfmvOPβ€’2mo ago
ohk
Chooβ™šπ•‚π•šπ•Ÿπ•˜
It looks like this code is guaranteed to never run more than once. After adding "marked" to the classList, a check is performed to determine if the classList does not contain "marked". It will contain "marked" due to the add(), so the loop condition will be false immediately after the first iteration, which means the loop won't execute another iteration.

Did you find this page helpful?