The do...while Loop in JavaScript
The do...while
iteration belongs to the category of exit-controlled loops. Simply put, this means that the loop body executes at least once, regardless of whether the test condition is true or false because it's evaluated and the end of the loop body rather than at the beginning like in the while
loop.
Do...while Loop Syntax
do {
// code to be executed
} while (test condition);
As we can see, the do
keyword marks the beginning of the loop body, followed by the code to be executed. On the third line, the while
keyword signals the end of the loop body, followed by the test condition in parentheses.
You may have already come across this, but the key difference between the do...while
and while
loops is that the first always executes the loop body at least once, whereas the latter may not execute the loop body at all if the test condition is false, to begin with.
Do...while Loop Examples
Using Do...While for a User Input Within a Range
Let's say we want to prompt the user to enter a number between 1 and 10 and keep prompting them until they do so.
let number;
do {
number = prompt("Please enter a number between 1 and 10");
} while (number < 1 || number > 10);
Initially, we ask the user to enter a number, and the test condition that we set up checks whether the number he entered is outside the specified range. If the number is outside of it, the loop executes again, asking the user to enter a new number. The loop will continue until the user enters a number within the range, and outputs it as a result.
Building a Blackjack Game with Do...While
To make things interesting, we could potentially simulate a game of blackjack where the player has to hit (draw a card) or stand (end their turn) based on their current hand. We can use the do...while
loop to keep the game going until the player decides to stand or their hand exceeds 21 (busts).
// Create an array of cards
const cards = [
"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"
];
// Initialize variables for the player's hand and total hand value
let hand = [];
let total = 0;
// Declare variables for the current card and the player's choice
let card;
let choice;
// Loop until the player chooses to stand or busts
do {
// Draw a card at random and add it to the player's hand
card = cards[Math.floor(Math.random() * cards.length)];
hand.push(card);
// Print the current hand
console.log(`Your hand: ${hand.join(", ")}`);
// Calculate the total hand value
total = hand.reduce((acc, val) => {
if (val === "A" && acc <= 10) { // Use an Ace as 11 or 1 based on the total value of the hand
return acc + 11;
} else if (val === "A" && acc > 10) {
return acc + 1;
} else if (["J", "Q", "K"].includes(val)) { // Face cards are worth 10
return acc + 10;
} else {
return acc + parseInt(val); // Numeric cards are worth their face value
}
}, 0);
// Check if the player has busted or won
if (total > 21) {
console.log("Bust! You lose.");
break;
} else if (total === 21) {
console.log("Blackjack! You win.");
break;
}
// Prompt the player to hit or stand
choice = prompt("Do you want to hit or stand?");
} while (choice.toLowerCase() === "hit"); // Loop as long as the player chooses to hit
// Print the final hand
console.log(`Your final hand: ${hand.join(", ")}`);