Difference between while and do-while loops


Trying to get an example where I can see the difference between while and do-while loops, it tried these two ones from the exercise here: https://www.codecademy.com/courses/introduction-to-javascript/lessons/loops/exercises/while.

While loop:

const cards = ['diamond', 'spade', 'heart', 'club']; let currentCard; while (currentCard != 'spade') { currentCard = cards[Math.floor(Math.random() * 4)]; console.log(currentCard); }; // Print example: diamond, diamond, heart, spade

Do-While loop:

const cards = ['diamond', 'spade', 'heart', 'club']; let currentCard; do { currentCard = cards[Math.floor(Math.random() * 4)]; console.log(currentCard); } while (currentCard != 'spade'); // Print example: diamond, club, club, spade

In both cases, I always get ‘spade’ at the end of the listed items, before the loop stops. When I check on internet I see that while shouldn’t print spade, and do-while should. Any idea on the reason I don’t have any difference in this example? Any other example where I could see the difference?

Thanks in advance for your precious help!

First time you run the while loop currentCard is undefined. Inside the loop you change the value of currentCard and then log it. If that value happens to be ‘spade’ it is logged to the console before the loop evaluates the condition.

do-while will always make at least a one iteration and then evaluates condition. On the other hand, while will evaluate the condition first, so might not make any iteration at all

Clear. Thanks for your explanation! :slightly_smiling_face: