Consider this scenario, you've been given a task to print out all even numbers between 0 and 100. Of course, you could do things the hard way like this:
1console.log(0);
2console.log(2);
3console.log(4);
4. . .
5console.log(100);
As you can imagine, this would be a tedious task. So, is there an easier way to solve this problem? Luckily, the answer is yes.
While loops
JavaScript provides a while
loop that executes the same piece of code repeatedly until the specified condition is violated.
For example, this is how you can print all even numbers between 0 and 100 using a while
loop:
1let n = 0;
2
3while (n <= 100) {
4 if (n % 2 === 0) {
5 console.log(n);
6 }
7
8 n = n + 1;
9}
10
22
34
46
58
6. . .
794
896
998
10100
First, we initiate a variable n
on line 1.
The keyword while
creates a while
loop. The expression n <= 100
is the condition. It will be executed for every loop iteration, and if the expression returns true
, the code block inside the curly braces will be executed. If it returns false
, the loop will stop.
In this particular example, the loop will be executed 101 times, from n = 0
to n = 100
.
Look inside the code block. The if
statement checks the parity of the number n
. If n % 2
equals 0
(the number n
can be divided by 2 without remainder), that means the number will be even and will be printed to the console.
Also notice that the value of n
is updated at the end of every loop iteration.
This step is very important. If left out, you will have an infinite loop that never stops. You can try the following code on your computer.
1let n = 1;
2
3while (n <= 10) {
4 console.log(n);
5}
This type of statement (updating a value based on its previous value) is so common that JavaScript created a shortcut for it.
1n += 1; // -> n = n + 1
2n += 2; // -> n = n + 2
3
4n -= 1; // -> n = n - 1
5n -= 2; // -> n = n - 2
6
7n *= 2; // -> n = n * 2
8
9n /= 2; // -> n = n / 2
And for the most commonly used n += 1
and n -= 1
, there is an even shorter expression.
1n++; // -> n += 1
2
3n--; // -> n -= 1
Do while loops
A do while
loop is a variant of the while
loop with the following syntax.
1do {
2 . . .
3} while (<condition>);
Unlike the while
loop, do while
guarantees the do
block executes at least once. After that, if the condition returns true
, the do
block will execute again. If not, the loop will terminate.
In practice, the do while
loop is often used to force a input from the user before the program can continue to the next step. For instance,
1let age;
2
3do {
4 age = prompt("How old are you?");
5} while (!age);
The prompt()
function will ask the user to provide their age, and the loop will execute over and over again until the user provides a non-empty input.
Note that the prompt()
function only works in the browser, so you must test the code in the browser's JavaScript console.