I have to create a function which takes an array as argument, with a forEach loop which console.log each element and each index for every iteration inside the function. Also inside the function declare a variable called count, and increment it by one for each iteration then return count.
//====================== EXAMPLE ======================== looper([2,4,8,7]) 4 // <====== EXPECTED OUTPUT //=========================================================
I wrote this function:
function looper(arr) { arr.forEach(function console (item, index){ var count = 0; count++; console.log(("I am item ", item, "I am the index ", index)); return count; }) }
But I get the following error:
VM76:5 Uncaught TypeError: console.log is not a function at console (<anonymous>:5:17) at Array.forEach (<anonymous>) at looper (<anonymous>:2:9) at <anonymous>:1:1
How is it that console.log is not a function? Isn’t it prebuilt into every browser?
Advertisement
Answer
count
should be declared and returned outside theforEach()
callback function. Otherwise you reset it to0
each time through the loop. And the return value offorEach()
is not returned by the containing function.The error about
console.log
not being defined is because you named the callback functionconsole
. That shadows the globalconsole
object. There’s no need to give a name to the callback function.You shouldn’t put an extra set of parentheses around the arguments to
console.log()
. This makes them an expression using the comma operator, so it only logs the last item in each call.
function looper(arr) { var count = 0; arr.forEach(function(item, index) { count++; console.log("I am item ", item, "I am the index ", index); }) return count; } console.log(looper([1, 3, 4, 10]));