In this article we will learn how to return a value from forEach
in JavaScript.
It is very common to return a value from forEach
in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to return a value from forEach
.
But we can't make forEach
return a custom value.
// Array
const array = [1, 2, 3, 4, 5];
// Wrong
const newArray = array.forEach(ele => {
if (ele % 2 != 0) {
return ele;
}
console.log(ele);
});
// `undefined`
console.log(newArray);
Output
undefined
How to solve this problem?
The solution to this problem is very easy. Yes, forEach does not return an output, but it is possible for us to define a variable outside the forEach
.
There are other solutions such as using filter
or reduce
methods.
Return value from forEach
using variables
We can define variable outside the forEach
and fill it.
Let's see an example
Now we have an array and we want to know what the largest number in that array is, then return that number
// Array
let array = [54, 64, 21, 65, 11, 5];
// Define variable
let result = 0;
// `forEach`
array.forEach(ele => {
if (ele > result) {
result = ele;
}
});
// Result:
console.log(result);
Output
65
Well, what if we want to return more than one number, i.e. filter the array and return more than one element from it.
Let's see an example
Now we want to return numbers greater than 30
// Array
let array = [54, 64, 21, 65, 11, 5];
// Define a variable
let result = [];
// Return numbers more than `30`
array.forEach(ele => {
if (ele >= 30) {
result.push(ele);
}
});
// Result:
console.log(result);
Output
[ 54, 64, 65 ]
Thank you for reading
Thank you for reading my blog. 🚀