anonymous-dev
anonymous-dev

Reputation: 3509

forEach not returning a value to outer function like for loop does

I was trying to put a return in my foreach, but it returns undefined. But when I put the same if statement in a for loop, it returns the correct value. Why is this happening?

this.SpriteAndHull.forEach(element => {
      if (element.name == name) {
        return element;
      }
});

Upvotes: 3

Views: 3246

Answers (3)

Kousha
Kousha

Reputation: 36219

What you want is find

// element will either ben the element that matches the name, or it will be undefined if nothing is found
const element = this.SpriteAndHull.find(el => el.name === name);

Upvotes: -2

mhodges
mhodges

Reputation: 11116

When using .forEach() Your return statement returns from the function being passed into the forEach callback, not the outer function.

Edit: It should be noted that returning from the .forEach() function does nothing, as .forEach() (by design) does not support a return value and will always return undefined

One thing you can do is to set the element and then return it, or simply use a different iterator function, like so:

function getElementByName(elems, name) {
  let elem;

  elems.forEach(element => {
    if (element.name === name) {
      elem = element;
    }
  });

  return elem;
}

or:

function getElementByName(elems, name) {
  return elems.find(element => element.name === name);
}

Upvotes: 5

T.J. Crowder
T.J. Crowder

Reputation: 1074929

Because forEach always returns undefined (in effect), and it completely ignores the return value of the callback, if any. Your return element is in the callback, so it's ignored.

You probably want a for-of loop instead:

for (const element of this.SpriteAndHull) {
    if (element.name == name) {
        return element;
    }
}

Upvotes: 3

Related Questions