Apps Script Course: Loops

Loops allow you to repeat one or more instructions a certain number of times, depending on one or more conditions.


For

To understand the benefit of loops, it's quite simple, observe this code:

function monthList() {

  console.log('Month 1');
  console.log('Month 2');
  console.log('Month 3');
  console.log('Month 4');
  console.log('Month 5');
  console.log('Month 6');
  console.log('Month 7');
  console.log('Month 8');
  console.log('Month 9');
  console.log('Month 10');
  console.log('Month 11');
  console.log('Month 12');
}

It's very repetitive... Now imagine there are 10,000 repetitions instead of 12...

Loops thus allow you to execute instructions in a loop to avoid unnecessary repetitions of code.

Here is a code that also displays the 12 messages but with a for loop:

function monthList() {

  const message = 'Month ';

  for (let i = 1; i <= 12; i++) {
    console.log(message + i);
  }
}

The for loop includes 3 expressions in (), separated by ;:

for (let i = 1; i <= 12; i++)

The first expression is the declaration of the variable that will serve as the counter (usually named i) and starts at 1 in this example to correspond to the month number:

let i = 1

The second expression is the condition that is true as long as i is less than or equal to 12 (to stop here at month 12):

i <= 12

And the third is the incrementation with i++ (which is equivalent to i = i + 1), meaning that after each iteration, the variable i increases by 1:

i++

Break

If necessary, you can exit a loop before the end using the break statement:

function monthList() {

  const message = 'Month ';

  for (let i = 1; i <= 12; i++) {
    console.log(message + i);

    // Exit the loop after "Month 6"
    if (i === 6) {
      break;
    }
  }
}

Exercise

To practice, complete the following code to display in the console the content of the array starting from the end (before moving to the solution a bit further down):

function loops() {

  const array = ['!', 'fun', 'are', 'loops'];

  for (   ) {
    console.log(  );
  }
}

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

Here is the completed version:

function loops() {

  const array = ['!', 'fun', 'are', 'loops'];

  for (let i = 3; i >= 0; i--) {
    console.log(array[i]);
  }
}

Starting from the end of the array (at index 3), the variable is therefore initialized at 3:

let i = 3

With a condition that goes down to the first value of the array (at index 0):

i >= 0

And the value of the variable is decreased by 1 with each loop (i-- is equivalent to i = i - 1):

i--

Finally, the value of the array is displayed based on the index i:

console.log(array[i]);