Color Keeper explainer


#1

Aim of the puzzle: Use the let keyword to set the value of a variable inside a for loop.
Walk through of solution: On the first line of the puzzle, you will see that a variable named color has been declared with the var keyword, and assigned the value 'yellow'. On the next line, the drawBox() function is called, taking color as an argument.

On the third line, there is a for loop. In the parentheses ( ) of the for loop, another variable named color is declared, this time with the let keyword. It is assigned to an array containing two elements: ['blue', 'green']. This means that the for loop will run twice (once for each element). For the first loop, let color = 'blue', and in the second loop, let color = 'green'.

The code block { } of the for loop has been left empty.

To complete the puzzle, call the function drawBox() inside the code block { } of the for loop, and give it the variable color as an argument. Add a second drawBox(color) below the for loop, on the line after the closing bracket }

When you run the finished puzzle, color is declared with the keyword var and given the value 'yellow'. A yellow box will be drawn. Inside the for loop, a second variable color is declared with the keyword let. Because this variable has been declared with let, it exists only inside the for loop. In programming, this is called “scope”. The let color variable is “scoped” to the for loop.

When drawBox(color) is called inside the for loop, it will look for the let color variable, because this variable is “scoped” to the for loop. When drawBox() is called outside with for loop, the program will only be able to see the var color variable.

Sample code solution:

var color = 'yellow';
drawBox(color);

for (let color of ['blue', 'green']) {
    drawBox(color);
}

drawBox(color);

Javascript Concepts: For Loop, Variable Declarations, Variable Scope, Arrays, Identifiers
Grasshopper Concepts: drawBox()