The for loop syntax looks like this:
for (let counter = 0; counter < 4; counter++) {
console.log(counter);
}
In this example, the output would be the following:
0
1
2
3
Let’s break down the example:
let counter = 0, so the loop will start counting at 0.counter < 4, meaning the loop will run as long as the iterator variable, counter, is less than 4.counter++. This means after each loop, the value of counter will increase by 1. For the first iteration counter will equal 0, for the second iteration counter will equal 1, and so on.console.log(counter), will execute until the condition evaluates to false. The condition will be false when counteris greater than or equal to 4 — the point that the condition becomes false is sometimes called the stop condition.const vacationSpots = ['Bali', 'Paris', 'Tulum'];
// Write your code below
for (let i = 0; i < vacationSpots.length; i++) {
console.log(`I would love to visit ${vacationSpots[i]}`);
}
Let’s break down what’s happening with our while loop syntax:
counterTwo variable is declared before the loop. We can access it inside our while loop since it’s in the global scope.while followed by our stopping condition, or test condition. This will be evaluated before each round of the loop. While the condition evaluates to true, the block will continue to run. Once it evaluates to false the loop will stop.counterTwoto the console and increments counterTwo.const cards = ['diamond', 'spade', 'heart', 'club'];
// Write your code below
let currentCard;
while (currentCard != 'spade') {
currentCard = cards[Math.floor(Math.random() * 4)];
console.log(currentCard);
}
In some cases, you want a piece of code to run at least once and then loop based on a specific condition after its initial run. This is where the do...while statement comes in.
A do...while statement says to do a task once and then keep doing it until a specified condition is no longer met. The syntax for a do...while statement looks like this: