0

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?

Dennis Kozevnikoff
  • 2,078
  • 3
  • 19
  • 29
  • 2
    You named your callback 'console', instead just pass an anonymous function, also, returning from `forEach()` has no effect, it always returns `undefined` per its definition. – pilchard Aug 16 '21 at 18:11
  • As @pilchard said you named you function console so thats why `.log` does not exist on it also your return statement has to be outside of the `forEach` loop to return the value – LeeLenalee Aug 16 '21 at 18:12
  • you can't use `console` as name's function. replace to : `arr.forEach(function(item, index){` – Mister Jojo Aug 16 '21 at 18:16

1 Answers1

4
  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]));
Barmar
  • 741,623
  • 53
  • 500
  • 612