while loop in JavaScript
The while
loop will run as long as an
expression passed to it as a parameter is
true. It allows you to perform an
arbitrary number of iterations.
Here is its syntax:
while ( while the expression is true ) {
executes this code cyclically;
at the beginning of each loop, we check the expression in parentheses
}
The loop will end when the expression is no longer true. If it was false initially, then it will never be executed.
Let's use the while
loop to sequentially
display numbers from one to five as an example:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
And now we will divide the given number by
2
as many times until the result
becomes less than 10
:
let num = 500;
while (num > 10) {
num = num / 2;
}
console.log(num); // the result
Print the numbers from 1
to
100
to the console.
Print the numbers from 11
to
33
to the console.
Given the number num
with some
initial value. Multiply it by 3
as many times until the result of the
multiplication is greater than 1000
.
What number will come out? Count the
number of iterations required for this.