To control the number of times a while
loop repeats, we start with a variable set to a number. We call this variable a counter variable.
let counter = 1;
Then, we use a comparison in the condition to compare the counter variable to a number. In this case, counter < 4
.
let counter = 1;
while (counter < 4) {}
Inside the code block, we make the condition return false
and stop the loop by incrementing the counter variable. Try it with counter++
.
let counter = 1;
while (counter < 4) {
console.log(counter);
counter++;
}