FAQ: Iterators - The .forEach() Method


#1

This community-built FAQ covers the “The .forEach() Method” exercise from the lesson “Iterators”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise The .forEach() Method

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

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


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


#4

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


#5

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!


#6

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().


#7

Question: in this code:

fruits.forEach(fruit => console.log(I want to eat a ${fruit}.))

Why do we drop the callback function name?

Why is it not:

fruits.forEach((function(fruit => console.log(I want to eat a ${fruit}.)))

to call as an anonymous function?


#8

you mean the function keyword? Because the arrow functions (=>) allows us to drop the function keyword. Of course you can go for:

function(fruit){ console.log(`I want to eat a ${fruit}.`) }

but you can’t combine function keyword with arrow function. That won’t work.


#10

Hey guys!
On Iterators - second page - Instruction 1 I’ve coded the following:

Code block 1:

fruits.forEach(fruit =>
 console.log('I want to eat ' + fruit));

Code block 2:

function printFruit(element){
  console.log('I want to eat ' + element);
}

fruits.forEach(printFruit);

Both display correct result however I still get error saying " In your callback function do you console.log() to print 'I want to eat _____ ? In the blank, you should concatenate or interpolate the element in fruits array?"


#11

your sentence is incorrect, the output should be:

I want to eat a apple

you output:

I want to eat apple

#12

When you focus on the important things you miss the little details. Pardon and thanks! :slight_smile:


#13

Why does the identifier change? I am able to pass this issue with the code below. Why is “fruit” accepted even though it isn’t’ declared? It seems like, with this and the examples, plurals are made into singulars in this situation. That doesn’t make sense to me, though.

fruits.forEach(fruit => console.log("I want to eat a " + fruit))


#14

Yes, but it is declared as the formal parameter of the function.

const callback = function (fruit) {
    console.log(`I want to eat a ${fruit}.`);
};
fruits.forEach(callback);

#15

Thanks for the reply! I’m happy to say that it clicked for me not long after I posted. I’ve been so used to the standard function writing format, that fat arrow is still resonating with me. “fruit” is the parameter which “fruits” is passed through as an argument, and using .forEach makes the individual strings of the array pass one at a time.


#16

When we don’t need this in our function, arrow syntax is nice and brief…

const callback = fruit => {
    console.log(`I want to eat a ${fruit}.`);
};

#17

So, because the result included “a apple”, the grammar was driving me nuts.
I created an “if statement”; however, I don’t completely understand the logic of how this code is working (as far as the element parameter). It seems there are different ways to use a callback. Could someone please help me understand? Here’s my code below:

const fruits = [‘mango’, ‘papaya’, ‘pineapple’, ‘apple’];

const allFruits = element => {
if (element != ‘apple’) {
console.log(I want to eat a ${element});
} else {
console.log(I want to eat an ${element});
}
}

fruits.forEach(allFruits);


#18

foreach is passing the elements to the callback parameter (element), one at a time and in order


#19

Thank you. So, allFruits is the callback with a parameter of “element”, which forEach passes to after being told to loop through the “fruit” array?


#20

no, foreach calls the callback function for each element in the list/array.

lets build our own very naive implementation:

function theForEach(theArray, theCallBackFunction){
  for (let i = 0; i < theArray.length; i++){
      theCallBackFunction(theArray[i]);
  }
}

const myArray = [1, 2, 3];

const myCallBack = element => {
  console.log(element);
}

theForEach(myArray, myCallBack);

theForEach represents the forEach method you currently use

i used slightly different syntax, otherwise i had to introduce a lot of new concepts


#21

That really cleared things up, thank you so much. So you just used the “for loop” opposed to forEach?