Repeating Instructions With Loops in JavaScript
JavaScript·30 min read·Jan 1, 2025
In programming, loops are control structures that allow you to repeat the execution of a set of instructions until a certain condition is met.
The while loop
The while loop is used to execute a set of instructions for as long as the specified condition remains true.
while (condition) {
instructions
}
Note: If on the first iteration the condition evaluates to
false, none of the instructions are executed.
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 variable named
numberand initialize it with the integer22. - Define a variable named
divisorand initialize it with the value of thenumbervariable. - Evaluate whether the value of
divisoris greater than0. - Evaluate whether the remainder of the division of
numberbydivisorequals0—which means thatdivisorevenly dividesnumber—and output the value ofdivisoriftrue. - Decrement the value of
divisorby1. - Repeat the
whileloop from step 3.
Which will produce this output:
22
11
2
1
Note: In JavaScript, the expression
--variableis equivalent tovariable = variable - 1.
The do...while loop
The do...while loop is used to execute a set of instructions for as long as the specified condition remains true.
do {
instructions
} while (condition);
Note: Unlike the
whileloop, it will execute the set of instructions at least once before the condition is evaluated.
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);
Note: The
console.log()function can be used to write to the standard output multiple values at once, when seperated by a comma character,.
When executed, it will:
- Define a variable named
baseand initialize it with the integer3. - Define a variable named
multiplierand initialize it with the integer1. - Define an uninitialized variable named
result. - Store the result of the multiplication of the
basevariable by themultipliervariable into theresultvariable. - Output in that order the value of the
basevariable, the string literal'*', themultipliervariable, the string literal'=', and theresultvariable. - Increment the value of the
multipliervariable by1. - Check if the current value of the
resultvariable is inferior to the value of thebasevariable multiplied by10and repeat thewhileloop from step 4.
Which will produce this output:
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
Note: 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.
The for loop
The for loop, inspired from the C language, is used to execute a set of instructions for as long as the specified condition remains true.
for (initialization ; condition ; afterthought) {
instructions
}
Where:
initializationis an expression executed once at the beginning of the loop and is typically used to set the initial values for loop control variables.conditionis an expression evaluated before each iteration of the loop and keeps the loop running until it evaluates tofalse.afterthoughtis an expression executed at the end of each iteration and is typically used to update loop control variables.
Note: Any variable declared within the
initializationwill only be accessible within the loop's body, between the curly brackets{}.
Example
Let's consider this script, that outputs the greatest common divisor of two integers:
const a = 56;
const b = 24;
const smallestValue = a <= b ? a : b;
let greatestDivisor = 1;
for (let divisor = 1 ; divisor <= smallestValue ; divisor++) {
if (a % divisor === 0 && b % divisor === 0) {
greatestDivisor = divisor;
}
}
console.log(greatestDivisor);
When executed, it will:
-
Define a variable named
aand initialize it with the integer56. -
Define a variable named
band initialize it with the integer24. -
Define a variable named
smallestValueand initialize it with the smallest value between theaandbvariables. -
Define a variable named
greatestDivisorand initialize it1, which is the smallest common divisor of theaandbvariables. -
Start a
forloop, where:let divisor = 0is used to initialize a variable nameddivisorthat will be used by the loop at each iteration.divisor <= smallestValueis used to evaluate whether the current value of thedivisorvariable equals the value of the smallest number and stop the loop iftrue.divisor++is used to increment the value of thedivisorvariable by1at each iteration of the loop.
-
Evaluate whether the
aandbvariables are both divisible by thedivisorvariable and store its current value into thegreatestDivisorvariable iftrue. -
Output the value of the
greatestDivisorvariable after theforloop terminates.
Which will produce this output:
8
Terminating and skipping loop iterations
In JavaScript, the break and continue statements allow you to control the execution flow of loops by either terminating them prematurely or skipping some iterations.
The break statement
The break statement is used to immediately terminate a running loop, regardless of whether the loop's condition is met or not.
loop
{
instructions
break;
}
Example
Let's consider this script, that outputs the individual characters of a string until it encounters the 's' character:
const word = 'javascript';
let index = 0;
while (true) {
if (word[index] === 's') {
break;
}
console.log(word[index]);
index++;
}
When executed, it will:
- Define a variable named
wordand initialize it with the string'javascript'. - Define a variable named
indexand initialize it with the integer0; - Start a
whileloop that will run indefinitely, since thetrueexpression always evaluates totrue. - Check if the character within the
wordat the currentindexis an's'and stop the loop's execution using thebreakstatement iftrue. - Otherwise, proceed to the next instruction and output the current character.
- Increment the value of the
indexvariable by1to move to the next character in the string. - Repeat the
whileloop from step 4.
Which will produce this output:
j
a
v
a
The continue statement
The continue statement is used to skip the current iteration of a loop and directly proceed to the next iteration, without executing the remaining instructions.
loop
{
if (condition) {
continue;
}
instructions
}
Example
Let's consider this script, that outputs all the numbers from 0 to 10 unless they are multiples of 2:
for (let number = 0; number <= 10; number++) {
if (number % 2 === 0) {
continue;
}
console.log(number);
}
When executed, it will:
- Start a
forloop based on thenumbervariable from0to10included. - Evaluate whether the current value of the
numbervariable is divisible by2and skip the remaining instructions using thecontinuestatement iftrue. - Output the value of the
numbervariable. - Repeat the
forloop from step 2.
Which will produce this output:
1
3
5
7
9
🗒️ Summary
Here's a summary of what you've learned in this lesson:
- The
whileandforloops are used to execute instructions for as long as the specified condition remainstrue. - The
do...whileloop is used to execute instructions at least once and for as long as the specified condition remainstrue. - The
breakstatement is used to immediately terminate a running loop. - The
continuestatement is used to skip the current iteration of a loop.
🤖 Projects
Here's a list of projects to apply what you've just learned:
- lb_diamond: Write a script that prints a diamond-shaped pyramid of variable size.
Unlock the Build CLI Apps in JavaScript & Node.js module
Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.
You get immediate access to:
- 45 focused lessons across JavaScript, Node.js, npm, and Git
- 17 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle