Explanation:
The aim of this puzzle:
Use console.log in order to see the code’s output and spot the logical error in the ‘picker’ function.
Walkthrough of the solution:
To see what is actually happening inside the code, we can insert a console.log. Keep in mind that due to variable scope, meaning that a variable is only accessible in the code block where it is declared, in this case within the for…in loop after ‘groceries’ is declared. This will show the following output:
Item currently in bag: undefined
Item currently in bag: undefined
Item currently in bag: undefined
This output is due to the variable declaration: let groceries = item[bag]; This logs as undefined because ‘bag’ is the array and ‘item’ is the index. In order to actually see the content of the array, the variable declaration should be: let groceries = bag[item];
Sample code solution:
(Tap below to reveal)
let whichGrocery= "Item currently in bag: ";
let groceryBag = {
fruit: ['banana', 'apple', 'cherry'],
vegetables: ['potatoe', 'carrot', 'celery'],
grains: ['cereal', 'pasta', 'bread']
}
function picker(bag) {
for(let item in bag) {
let groceries = item[bag];
console.log(whichGrocery+groceries);
}
}
picker(groceryBag.vegetables);
JavaScript Concepts: Variable declaration, object expression, arrays, function declaration, console.log, function call