How to prevent the last statement from being logged to the console in a while loop?

Viewed 47

Consider the following code:

const cards = ['diamond', 'spade', 'heart', 'club'];

let currentCard;
while (currentCard !== 'spade'){
  currentCard = cards[Math.floor(Math.random() * 4)];
  console.log(currentCard);
}

The result also logs spade to the console.

Is there any way to avoid this? I want to avoid the last statement from being logged to the console in this while loop.

Thanks in advance!

3 Answers

You could loop forever and break with an if statement.

const cards = ['diamond', 'spade', 'heart', 'club'];

let currentCard;
while (true) {
    currentCard = cards[Math.floor(Math.random() * 4)];
    if (currentCard === 'spade') break;
    console.log(currentCard);
}

The While evaluation only runs before the first run, and after the code within the scope has finished. You are going to want to add a check inside the while loop before logging.

if (currentCard == 'spade') 
  break;

My understanding - You are always logging the next card

2 ways that in which this can be done are:

const cards = ['diamond', 'spade', 'heart', 'club'];

let currentCard;
while (currentCard !== 'spade'){
  currentCard = cards[Math.floor(Math.random() * 4)];
  (currentCard !== 'spade')?console.log(currentCard):'';
}

2nd way: Here the logging is being done in next iteration. Thus you may observe an extra '' [empty string] being logged

const cards = ['diamond', 'spade', 'heart', 'club'];

let currentCard;
while (currentCard !== 'spade'){
  console.log(currentCard);
  currentCard = cards[Math.floor(Math.random() * 4)];
}
Related