1

I have a function for a game I am creating:

var getFireableLaser = function() {

  var result = null;
  lasers.forEach(function(aLaser) {
    if(aLaser.y <= -120) {
      result = aLaser;
    }
  });
  return(result);

}

it goes through an array of 'laser' objects and returns one when the if condition is met, however if i write the code like this:

var getFireableLaser = function() {

  lasers.forEach(function(aLaser) {
    if(aLaser.y <= -120) {
      return(aLaser);
    }
  });
  return(null);

}

the function only returns null? Why is it that when I do var laser = getFireableLaser(); in another function expression, laser is null when i console.log it? (in that specific other function);

When I console.log(aLaser) just before I return it, it shows the laser object. So why is it that the returned object is null and saved as null?

CoderTn
  • 985
  • 2
  • 22
  • 49
H.Lin
  • 13
  • 4
  • 1
    In the second case, your internal `return` is only returning from the function you give to forEach. – Denys Séguret Jul 20 '18 at 07:17
  • The syntax is `return null;` and not `return(null);` – JSON Derulo Jul 20 '18 at 07:19
  • `Array.forEach` returns `undefined`, hence, anything you return in the function is not delegated further to the function. However, you can use a `for loop`, in which a return statement delegates it to the function. For e.g. - http://plnkr.co/edit/Vq7rlEusTxRIq3VkUbbk?p=preview – Nikhil Aggarwal Jul 20 '18 at 07:29

1 Answers1

1

forEach ignores whatever you return to it - returning from it doesn't break out of the forEach and return from the outer function, it simply stops the current iteration and goes onto the next iteration.

You might use .find instead:

var getFireableLaser = function() {
  return lasers.find(aLaser => aLaser.y <= -120);
}

(though, .find returns undefined, not null, when a match isn't found)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you for the help, just for my curiosity, what happens to the var laser = getFireableLaser(); when the return(laser) line is run inside of the forEach? Or what is that line returning to? Where did that laser object inside of the return statement go? Basically, where is my return object being sent – H.Lin Jul 20 '18 at 17:42