How do you prevent undefined from logging as well after using .forEach Iterator on an array?

After attempting this exercise, by using the .forEach iterator on an array, the code runs correctly. However, undefined still shows below the code.

I understand by default, that the .forEach iterator method returns undefined. How can I log my results without displaying the undefined along with it?

The link you gave takes us to the exercise, but it doesn’t give us your code. Use the “Preformatted text” option in the text box to post your code here so we can see what code you’re working with.

This s the code here…

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

// Iterate over fruits below

const eatDuty = fruits.forEach(fruit => {

  console.log("I want to eat a " + fruit);

});

console.log(eatDuty);

If you understand that the .forEach method returns undefined, why capture this in a variable (eatDuty) and why log it?

Kindly explain, please.

So how can the iterator be useful?

The forEach method is useful if we want to do something which doesn’t need to use return

why do you mean by iterator?

Okay! It makes sense now. But kindly give an example of something that may not need to use return.

As for this…

I thought .forEach method is an example of an iterator.

A function for purely printing something in a pretty way. Or any other case where you don’t need to hand back data to the caller.

Here’s a trivial example:

const stuff = ["dogs", "cats", "pizza", "kale", "baseball", "soccer"];

stuff.forEach((thing, index) => console.log(`I ${index % 2 ? "don't " : ""}like ${thing}.`));

Output:

I like dogs.
I don’t like cats.
I like pizza.
I don’t like kale.
I like baseball.
I don’t like soccer.