Skip to content Skip to sidebar Skip to footer

Es6 Class Methods Not Returning Anything Inside Foreach Loop

For some reason the method getTwo() inside the PollClass won't return 2 but undefined. If I put the return statement outside the .forEach() loop a value does get returned however.

Solution 1:

An arrow function is still a function, and you're only returning from the forEach callback function, not from getTwo, you have to return from the getTwo function as well.

It's not quite clear why you would use a loop to check for something in that way, but the concept would be something like

getTwo() {
    var n = 0;
    this.nums.forEach(num => {
      if (num === 2) n = num;
    })
    return n; // returns something from getTwo()
  }

Solution 2:

As adeneo mentioned, you must return from the getTwo function to achieve what you want. Returning from the callback passed into forEach, regardless if its an arrow function or not, doesn't return from forEach itself.

Alternatively to forEach, you can use find which you can write in less code and return directly:

getTwo() {
  returnthis.nums.find(num => num === 2);
}

Post a Comment for "Es6 Class Methods Not Returning Anything Inside Foreach Loop"