Repeat Instructions With the while Loop in JavaScript
9 min read·Jan 1, 2025
In programming, loops are control structures that allow you to repeat the execution of one or more statements until a certain condition is met.
loop {
statements
}
Where:
loopis a control structure likewhileorfor.{}is the block statement used to group the statements executed by the loop.statementsis a list of zero or more statements.
💡 The complete execution of all the statements of a loop is called an iteration.
The while loop
The while loop is used to execute a set of statements for as long as the specified condition remains true. This loop is mostly used when the total number of iterations is unknown and depends on something happening.
while (condition) {
statements
}
💡 If on the first iteration the condition evaluates to
false, none of the statements are executed and the loop terminates immediately.
⚠️
whileloops can easily turn into infinite loops if you forget to update the value of the condition's variable(s) that will eventually make the conditionfalse.
Example
Let's consider this script, that outputs a countdown:
let liftoff = false;
let countdown = 3;
while (liftoff === false) {
console.log(countdown);
countdown++;
if (countdown === 0) {
liftoff = true;
}
}
console.log("Liftoff!");
When executed, it will:
-
Define a
liftoffvariable and initialize it with the booleanfalse. This variable will be used to determine whether the rocket has launched. -
Define a
countdownvariable and initialize it with the integer3. This variable will be used to keep track of the launch countdown. -
Define a
whileloop that will run untilliftoffevaluates totrue.- Output the current value of
countdown. - Decrement the value of
countdownby 1. - Set
liftofftotrueifcountdownequals 0.
- Output the current value of
-
Output the string
"Liftoff!".
Which will produce this output:
3
2
1
Liftoff!
Example
Let's consider this script, that prints all the divisors (or factors) of a number, which are the integers that evenly divide it:
const number = 22;
let divisor = number;
while (divisor > 0) {
if (number % divisor === 0) {
console.log(divisor);
}
--divisor;
}
When executed, it will:
-
Define a
numbervariable and initialize it with the integer22. This variable is the number to divide. -
Define a
divisorvariable and initialize it with the value of thenumbervariable. This variable will be used to find the list of divisors. -
Define a
whileloop that will run untildivisoris equal to or less than 0.- Output the value of
divisorif the remainder of the division ofnumberbydivisorequals0— which means thatdivisorevenly dividesnumber. - Decrement the value of
divisorby1.
- Output the value of
Which will produce this output:
$ node print_divisors.js
22
11
2
1
💡 In JavaScript, the expression
--variableis equivalent tovariable = variable - 1.
The do...while loop
The do...while loop is used to execute a set of statements for as long as the specified condition remains true. This means that the loop will execute the statements at least once before the condition is evaluated.
do {
statements
} while (condition);
Example
Let's consider this script, that outputs the multiplication table of a number:
const base = 3;
let multiplier = 1;
let result;
do {
result = base * multiplier;
console.log(base, '*', multiplier, '=', result);
multiplier++;
} while(result < base * 10);
💡 In JavaScript, the
console.log()function can be used to write multiple values to the standard output at once, when seperated by a comma character,.
When executed, it will:
-
Define a
basevariable and initialize it with the integer3. -
Define a
multipliervariable and initialize it with the integer1. -
Define a undefined
resultvariable. -
Define a
do...whileloop.- Store the value of
basemultiplied bymultiplierintoresult. - Output the formatted operation and result.
- Increment the value of
multiplierby 1. - Check whether
resultis less thanbasemultiplied by10.
- Store the value of
Which will produce this output:
$ node mult_table.js
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
💡 Since the
do...whileloop executes its instructions before evaluating its condition, we must use the<comparison operator rather than<=, as otherwise the loop would have stopped at3 * 11 = 33.
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery