-1

I have a function that loops through a list using forEach and I want to return a result early (mimicking break). But the function returns undefined. Why does it return undefined?

Here's the fiddle.

const list = [1, 2, 3];
const test = () => {
  const rs = list.forEach(item => {
    return item
  })
   return rs
}
const rs = test()

console.log(rs)
jarmod
  • 71,565
  • 16
  • 115
  • 122
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

4 Answers4

0

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)
jarmod
  • 71,565
  • 16
  • 115
  • 122
Nicolas
  • 8,077
  • 4
  • 21
  • 51
0

If you want to know if there is something in the list you need this - note test needs to return something for the log to show anything

const list = [1, 2, 3];
const test = () => {
  const rs = list.filter(item => {
    return item!=null
  })
  return rs.length>0;
}
const rs = test()

console.log(rs)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

By definition, forEach return undefined. see this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

you can use map instead,which returns an array and do not forget to return it in a map

const list = [1, 2, 3];
const test = () => {
  const rs = list.map(item => {
      return item
  })
  return rs;
}
const rs = test()
MING WU
  • 2,962
  • 1
  • 12
  • 16
0

Fix this problem this way.

const list = [1, 2, 3];
const test = () => {
  const rs = [];
list.forEach(item => {
    rs.push(item);
  })
   return rs;
}
const rs = test();

console.log(rs);
A.R.SEIF
  • 865
  • 1
  • 7
  • 25