Early Riser explainer

Aim of the puzzle: Use a classic for loop to iterate over every other element in an array.
Walk through of solution:
A classic for loop has 3 parts:

  1. A start condition that declares a variable and gives it a value.
  2. A test that keeps the classic for loop running as long as the test is true.
  3. An update operation that changes the variable after each iteration.

We can use classic for loops to iterate through an array. For example, in the following code:

let veggies = ['spinach', 'broccoli', 'zucchini'];
for (let i = 0; i < veggies.length; i++) {

veggies has elements at indices 0, 1, and 2. The length property of veggies is 3, as there are 3 total elements.

The classic for loop declares the variable i and sets it to 0. The for loop will run as long as i is less than veggies.length, which is 3. After each iteration, i++ will add 1 to the value of i.

In the 1st iteration, i is 0, so console.log(veggies[i]) will print 'spinach'. In the next iteration, i is 1, so 'broccoli' will be printed, and so on.

To complete this puzzle, change the update portion of the for loop’s setup to i += 2. Then change the string in the code block to '6am'.
Sample code solution:

import { alarmTimes } from 'grasshopper.alarm';
for (let i = 0; i < alarmTimes.length; i += 2) {
    alarmTimes[i] = '6am';


Javascript Concepts: Classic For Loops, Variable Declarations with Let, Arrays, Array Indexing, Iteration, console.log(), Import Declarations
Additional Code (hidden code that runs before the puzzle’s code):

let alarmTimes = [...Array(7)].map(_ => '8am');
1 Like