Skip to content
Advertisement

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

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.

JavaScript

I wrote this function:

JavaScript

But I get the following error:

JavaScript

How is it that console.log is not a function? Isn’t it prebuilt into every browser?

Advertisement

Answer

  1. count should be declared and returned outside the forEach() callback function. Otherwise you reset it to 0 each time through the loop. And the return value of forEach() is not returned by the containing function.

  2. The error about console.log not being defined is because you named the callback function console. That shadows the global console object. There’s no need to give a name to the callback function.

  3. 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.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement