Why does .forEach() return undefined?

Why is the return value for .forEach() always undefined?

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below
fruits.forEach( fruit => {
  let indefiniteArticle = '';
  if (fruit[0] === 'a' || fruit[0] === 'e' || fruit[0] === 'i' || fruit[0] === 'o' || fruit[0] === 'u') {
    indefiniteArticle = 'an';
  } 
  //else if (fruit[0] === 'h'&& fruit[1] ===) { }
  else {
    indefiniteArticle = 'a';
  }
  console.log(`I want to eat ${indefiniteArticle} ${fruit}`);
});

/* Added indefinate article conditions. 
For future senerio, implment conditions with words starting with an H.
Also obeying DRY, create an array of vowels to loop through to avoid rewriting each vowels condition on the H comparison. */

I included Indefinate Article conditions to make an apple grammatically correct.

why would this method need to return anything? What matters are the values you get from the array

1 Like

Hi
MDN and the instruction in the Codecademy say that .forEach() always return undefined!!
The question is why and even how we can get this while in codes I’ve seen, it always return something but undefined!

Array.forEach() does return undefined, but never anything else. It iterates over an array and acts upon its elements in the manner we instruct by way of our callback.

Let’s demonstrate this…

 > function print (x) {
     console.log(x);
     return 0;
   }
<- undefined
 > [1,2,3,4,5,6,7,8,9].forEach(print)
   1
   2
   3
   4
   5
   6
   7
   8
   9
<- undefined

The last line is the echoed response to the command entered.

 > print([1,2,3,4,5,6,7,8,9].forEach(print))
   1
   2
   3
   4
   5
   6
   7
   8
   9
   undefined
<- 0

The 0 is the return from the print function. It is ignored by the iterator when the function is given as a callback.

 > console.log([1,2,3,4,5,6,7,8,9].forEach(print))
   1
   2
   3
   4
   5
   6
   7
   8
   9
   undefined
<- undefined

The last value is the logged return from .forEach().

1 Like

What does it mean the: The return value for .forEach() will always be undefined

Thank you

 > list = [1, 2, 3, 4, 5, 6]
 > console.log(list.forEach(x => x * 2))
   undefined
<- undefined
 > console.log(list.map(x => x * 2))
<- [2, 4, 6, 8, 10, 12]
<- undefined

One method has no return value, the other does.