Why does .forEach() return undefined?

It is so hard to understand .forEach() return undefined? If it returns undefined so why are we using it?

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

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

.forEach() method returns here

I want to eat a mango
I want to eat a papaya
I want to eat a pineapple
I want to eat a apple

As you see it returns VALUE.

So why you are calling that .forEach() returns undefined?

2 Likes

You use the method to log each item of the array to console.

logging something to the console and the value returned by a method are two different things.

doing:

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

will show you the return value, which is undefined

just like when we would define a function/method that doesn’t have a return keyword

2 Likes

I just like to clarify what roy said above, so it means that the forEach() method purpose only is if we want to perform an action in an array such as accessing an element in an array, forEach() method will only help us access those element in an array and pass those elements in a callback function defined as argument of the forEach() method right? that’s why it doesn’t expect any return value as it’s only purpose is to help us access elements, which is a great alternative, rather than using for loop.

So basically, the return value will always depend on the callback function that we will be going to defined and passed an argument? just like the example above which performs an arrow function with implicit return value. That’s how I understood the purpose of forEach() method. am I right?. Please correct me if I’m wrong. Thank you so much.

1 Like

The difference between logging and returning value is that, if we want to perform certain actions inside the function and we want to get those results and use those results on other functions or assign the result value to a new variable globally, then the returned keyword is what we need. We should define it inside of our functions.

const val1 = 1;
const val2 = 2;

function sumWithReturn(a, b) {
	let sum = a + b;
	return sum; 
}

returning value means we can use the value for performing other actions globally, such as assigning it’s value to a new variable. If we try to log the returned value of the above function, it will display it to the console.

// will log the sum as it returns the value, and value can be access and used globally
console.log(sumWithReturn(val1, val2)); 
// used the returned value of the sumWithReturn function and assign it to a variable
const sum = sumWithReturn(val1, val2); 
// log the value of sum
console.log(sum); 
// without returning value, sum variable can be only access inside this code block / locally
// that's why if we tried to log this function, it will return an undefined, but it performs the actions inside
function sumNoReturn(a, b) {
	let sum = a + b;   
}
// will only returned undefined, but performs actions inside the function.
console.log(sumNoReturn(val1, val2)); 

// this function will log the value of the sum 
// but it doesn't return its values
// if we try to print it, it will return an undefined

function sumWithLog(a, b) {
	let sum = a + b; 
  console.log(sum); 
}

// logging the function will returned undefined but it will log the value of sum as we defined a console.log() inside the function.
console.log(sumWithLog(val1, val2)); 
4 Likes

… in Read Only mode.

2 Likes

“… in Read Only mode.”

Ah, that’s a key point, thanks.

1 Like

Well, I’ve looked through all of these and I still don’t understand how forEach() always returns undefined, lots of people posted code that is too complex for me since this is an intro class and I am just learning how to do this. And other people are posting saying they’re demonstrating how it “returns” undefined, and there is no return in there code. Maybe I am missing something, probably I’m missing something actually. Would be grateful for some enlightenment, thank you.

2 Likes

Every function has a default return.

const foo = x => {

}
console.log(foo())    //  undefined

Functions that perform an action but have nothing to send back all return the same way. Methods are functions and behave identical. .forEach() is a method that performs an action and has nothing to send back. The return value will always be undefined.

1 Like

holy moly how are you supposed to read this?

2 Likes

Welcome, @script6290548171, to the world of expressions.

console.log()

is an expression since it has a return value, undefined It’s also a statement since it triggers standard output mechanisms to come to life.

It’s not necessarily the first expression we learn, but one of the first since we need it going forward working in the console environment.

a = a + 1

is likely one of the first statements we learn, and get an understanding of. a + 1 is an expression, namely the value resulting from 1 being added to the present value of a. In the above statement we assigned this new value to a. The old value that was represented in the expression on the right is replaced with the new value once the expression is evaluated.

We’re logging a string expression that uses back tick quotes to indicate it contains template literals. Those devices are expressions, which can be any form so long as they yield a value. ${ ... } will be cast to string whatever the value that results. In the above example the result is one of an or a being inserted into the string. The other template literal contains the value we are examining at the moment.

1 Like

Hello
Thanks for all questions and explanation of the ‘undefined and return difference’ .forEach method above. I understood well and my code was OK, i coded the easy one with ‘a’ and ignored ‘an’. Then i found the different codes and i tried it:
console.log(I want to eat ${aeiou.includes(fruitChoice.charAt(0))? an:a} ${fruitChoice}.);
)
the error is saying ‘missing ) after argument list’ . I cannot find any missing thing in my code. Could you please see my code where i am wrong ?
Thank you

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

fruits.forEach (fruitChoice => 
  console.log(`I want to eat ${`aeiou`.includes(fruitChoice.charAt(0))? `an`:`a` } ${fruitChoice}.`);
)

It may be that because there is a newline, curly braces are needed on the callback function body.

 y.forEach(x => {
     console.log(...)
 })

Aside

You do know that copying solutions is not the way to learn. Scrap all of the above and work it out on your own from scratch. It will have a more lasting effect and you will learn from trial and error while your brain sorts out the logic.

Hello Mtf

Thank you and it is ok now , You are right , i forgot { } in arrow function .

Thanks again for your advice too but i have already got my code on my own which is very sample because I followed as per exercise instruction. Then i read through all other people opinions in here and i have tested ‘aeiou’ one but i have a problem of checking ‘syntax’ and it showed always error. I can do different types of function for ‘aeiou’ .include method . Here is my original codes. Again , as you can see, in second function, i didn’t use { } but the code is working ( i know i supposed to use {} in arrow function too) . Now all ok.

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

// Iterate over fruits below
//I practise two ways of functions
fruits.forEach(function(fruitChoice) {
console.log(I want to eat a ${fruitChoice}.)
})
fruits.forEach (fruitChoice =>
console.log(I want to eat a ${fruitChoice}.)
)

1 Like