The aim of this puzzle:
Use console.log to find a bug in the showList function and then correct it
Walkthrough of the solution:
There’s something wrong with the function, in order to see what it is we begin by changing the return statement to a console.log in order to see what the code’s output is. After putting in the console.log, we see that the code’s output is:
sugar
Something’s not quite right, we only see the last element in the ingredientsList array when we want to see each item. One way to troubleshoot this is to consider the index of ‘sugar’, which is 5. If we look at the classic for loop, we see that the variable ‘i’ is declared as 5, which corresponds with the index of ‘sugar’. By changing this to let i = 0, the for loop will beginning looping from the beginning of the array, or the 0 index, and log each element of ingredientsList to the console.
Sample code solution:
(Tap below to reveal)
let ingredientsList = [
'flour',
'salt',
'milk',
'eggs',
'baking powder',
'sugar'
];
function showList(list) {
for(let i = 5; i < list.length; i++) {
return list[i];
}
}
showList(ingredientsList);
JavaScript Concepts: Arrays, function declaration, classic for loop, console.log, function call
It’s the code after the logic error has been corrected. You use the console.log() to find the error and then fix the error. It should actually let i = 0.
You want the whole list displayed on the console, you’re right that the answer must have for loop.
Problem is the silly grasshopper forgot the rule that low starting numbers go with ++, and high starting numbers go with --.
Grasshopper put in a high starting number, and a ++.
Fix that.
You want the list[i] logged on the console. You’re right there has to be something in the for loop. Problem is the silly Grasshopper put the wrong thing in there, a return, which ends the for loop without logging anything into the console.
Fix that.