Skip to content

While Loop : JS

Marie-Louise edited this page Feb 1, 2019 · 5 revisions

While loops have a similar structure as For Loops, but without the counters. They are used whenever its not clear how many time something needs to loop

Below the cards array, declare a variable, currentCard, with the let keyword but don't assign it a value.

while loop with a condition that checks if the currentCard does not have that value 'spade'.

Math.floor(Math.random() * 4) will give us a random number from 0 to 3. We'll use this number to index the cards array, and assign the value of currentCard to a random element from that array.

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

let currentCard;

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

Do...While

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:

const cupsOfSugarNeeded = 1;
const cupsAdded = 0;

do { cupsAdded++
} while (cupsAdded < cupsOfSugarNeeded);

this example - increments cupsAdded by one while cupsAdded is less than cupsOfSugarNeeded.

The break keyword allows programs to “break” out of the loop from within the loop's block

Clone this wiki locally