Premium lesson

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:

  1. Define a variable named number and initialize it with the integer 22.
  2. Define a variable named divisor and initialize it with the value of the number variable.
  3. Evaluate whether the value of divisor is greater than 0.
  4. Evaluate whether the remainder of the division of number by divisor equals 0—which means that divisor evenly divides number—and output the value of divisor if true.
  5. Decrement the value of divisor by 1.
  6. Repeat the while loop from step 3.

Which will produce this output:

22
11
2
1

Note: In JavaScript, the expression --variable is equivalent to variable = 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 while loop, 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:

  1. Define a variable named base and initialize it with the integer 3.
  2. Define a variable named multiplier and initialize it with the integer 1.
  3. Define an uninitialized variable named result.
  4. Store the result of the multiplication of the base variable by the multiplier variable into the result variable.
  5. Output in that order the value of the base variable, the string literal '*', the multiplier variable, the string literal '=', and the result variable.
  6. Increment the value of the multiplier variable by 1.
  7. Check if the current value of the result variable is inferior to the value of the base variable multiplied by 10 and repeat the while loop 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...while loop executes its instructions before evaluating its condition, we must use the < comparison operator rather than <=, as otherwise, the loop would have stopped at 3 * 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:

  • initialization is an expression executed once at the beginning of the loop and is typically used to set the initial values for loop control variables.
  • condition is an expression evaluated before each iteration of the loop and keeps the loop running until it evaluates to false.
  • afterthought is an expression executed at the end of each iteration and is typically used to update loop control variables.

Note: Any variable declared within the initialization will 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:

  1. Define a variable named a and initialize it with the integer 56.

  2. Define a variable named b and initialize it with the integer 24.

  3. Define a variable named smallestValue and initialize it with the smallest value between the a and b variables.

  4. Define a variable named greatestDivisor and initialize it 1, which is the smallest common divisor of the a and b variables.

  5. Start a for loop, where:

    • let divisor = 0 is used to initialize a variable named divisor that will be used by the loop at each iteration.
    • divisor <= smallestValue is used to evaluate whether the current value of the divisor variable equals the value of the smallest number and stop the loop if true.
    • divisor++ is used to increment the value of the divisor variable by 1 at each iteration of the loop.
  6. Evaluate whether the a and b variables are both divisible by the divisor variable and store its current value into the greatestDivisor variable if true.

  7. Output the value of the greatestDivisor variable after the for loop 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:

  1. Define a variable named word and initialize it with the string 'javascript'.
  2. Define a variable named index and initialize it with the integer 0;
  3. Start a while loop that will run indefinitely, since the true expression always evaluates to true.
  4. Check if the character within the word at the current index is an 's' and stop the loop's execution using the break statement if true.
  5. Otherwise, proceed to the next instruction and output the current character.
  6. Increment the value of the index variable by 1 to move to the next character in the string.
  7. Repeat the while loop 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:

  1. Start a for loop based on the number variable from 0 to 10 included.
  2. Evaluate whether the current value of the number variable is divisible by 2 and skip the remaining instructions using the continue statement if true.
  3. Output the value of the number variable.
  4. Repeat the for loop 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 while and for loops are used to execute instructions for as long as the specified condition remains true.
  • The do...while loop is used to execute instructions at least once and for as long as the specified condition remains true.
  • The break statement is used to immediately terminate a running loop.
  • The continue statement 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.
icon light bulb key

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
Unlock this module