The aim of this puzzle: Change every other value in the array to '8pm'
.
Walkthrough of the solution: The closingTimes
array is imported from 'grasshopper.store'
. It starts out with each element as '5pm'
. The For Loop goes through each item as sets the value to '5pm'
, but that doesn’t really change anything because it’s the same value. Change the '5pm'
to '8pm'
.
Now if you run the code, all the values are changed to '8pm'
, but we were only supposed to make every other value '8pm'
. Notice that the i
variable determines which array index to use. We want to change the elements at index 0, 2, 4, and 6. That means, we want to increase i
by 2 each loop instead of 1. Change i += 1
in the For Loop setup into i += 2
.
Sample code solution:
(Tap below to reveal)
import { closingTimes } from 'grasshopper.store';
console.log(closingTimes);
for (let i = 0; i < closingTimes.length; i += 2) {
closingTimes[i] = '8pm';
}
console.log(closingTimes);
JavaScript Concepts: Array Indexing, Assignment Operator (+=), Code Block (for loop), import
, .length()
Additional Code (hidden code that runs before the puzzle’s code):
let closingTimes = ['5pm', '5pm', '5pm', '5pm', '5pm', '5pm', '5pm'];