Comfort Food explainer


#1

The aim of this puzzle: Update the found variable when you find your favorite on the menu

Walkthrough of the solution: The askServer function takes in a string that is the name of your favorite food. Then it creates a variable called found which represents whether or not you’ve found the name of your favorite on the menu. Since the function hasn’t checked through the menu yet, the value of found should start as false.

The for…of loop will go through each entry of the menu. It takes the first entry and stores it in the variable called element. Then it goes to the if statement that checks if your favorite is the same as the menu entry it’s holding onto right now (element). If they aren’t equal, then that if statement gets skipped and the for…of loop takes the next item in the menu and stores that in the element variable. It keeps doing this with each item in the menu.

If at some point the element is equal to your favorite, that means your favorite is on the menu and you should set the found variable to true. After that, if there are any more items in the menu, it will keep checking them.

Once all the items in the menu are checked, it moves on to the second if statement which takes a look at the found variable. If you were able to check all the items in the menu without ever changing the found variable to true, then it would still be false and that means your favorite isn’t on the menu.

Sample code solution:
(Tap below to reveal)

function askServer(favorite) {
  var found = false;
  for (var element of menu) {
    if (favorite === element) {
      found = true;
      console.log('We have ' + favorite);
    }
  }
  if (found === false){
    console.log('Sorry, no ' + favorite);   
  }
}
askServer('cake');
askServer('milk');

JavaScript Concepts: Arithmetic Operators (+ concatenation), Assignments, Binary Expression (+), Code Block (function, for loop)
Grasshopper Concepts: print()
Additional Code: There is hidden code that runs before the puzzle’s code that creates the variable menu.


#2

How do I get the ‘print’ function to show up. It’s not giving me the option to use that


#3

The print() calls were from an older version of the card (before we had any puzzles using console.log()). I’ve updated the answer here to use console.log(). Thanks!

–Frankie