The function forEach
does not return a value. You'd be better off using find
. At this point, it's unclear what you want to do with your loop so I'm assuming that you are trying to return a value based on a condition.
From MDN
forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.
Also, the way you are calling your function is wrong. You are setting a variable inside a callback but never returning the variable. The test
function returns nothing. Hence you get undefined.
You should return the value of the find
function.
const list = [1, 2, 3];
const test = () => {
return list.find(item => {
if(/* some condition */ item > 1) {
return item
}
})
}
const rs = test()
console.log(rs)