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.

//======================  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

  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.

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]));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement