Family Magazine

While Loops in JavaScript

By Geoff Griffiths @mmatraining1980

A while loop is more versatile than a for loop.

A while loop just needs a condition to keep running.

Creating a while loop

  • Add a condition.

for example

while ((rep<=10)

Run the look while the “rep” value is less than or equal to 10

  • Add the staring condition:

let rep = 1;

  • add the code to be executed:

console.log(‘lifting weights repetition ${rep}

  • Add the counter:

rep++;

let rep=1;
while (rep <=10) {
console.log('lifting weights repetition ${rep});
rep++;
}


While Loop doesn’t need a counter

Random variable – throwing a dice until we throw a 6

We don’t know how many times the dice has to be thrown, so we don’t need a counter

let dice = Math.trunc(Math.random() x 6) + 1;
console.log(dice);

while (dice !==6) {
console.log('Your rolled a ${dice}');
}



while (dice !==6) is the condition – roll the dice whilst the condition is not equal to 6


Back to Featured Articles on Logo Paperblog