Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can forEach in JavaScript make a return? [duplicate]

I wonder if forEach in JavaScript can make a return, here is my code:

var a = [0, 1, 2, 3, 4];

function fn(array) {
  array.forEach(function(item) {
    if (item === 2) return false;
  });

  return true;
}

var ans = fn(a);
console.log(ans); // true

I want to find out if 2 is in my array, if so, return false, but it seems that the forEach function has looped the whole array and ignore return.

I wonder if I can get the answer I want with forEach ( I know I can get what I want using for(..))? dear friend, pls help me, with great thanks!

like image 947
hanzichi Avatar asked Aug 17 '15 02:08

hanzichi


3 Answers

You can use indexOf instead https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

function fn(array) {
  return (array.indexOf(2) === -1);
}

Also from the documentation for forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead.

So, the return value cannot be used the way you are using it. However you could do a throw (which is not recommended unless you actually need an error to be raised there)

function fn(array) {
  try {
      array.forEach(function(item) {
         if (item === 2) throw "2 found";
      });
  }
  catch (e) {
    return false;
  }

  return true;
}
like image 125
potatopeelings Avatar answered Oct 05 '22 13:10

potatopeelings


In this case .indexOf() is probably what you want, but there's also .some() when a simple equality comparison is too simple:

var ans = a.some(function(value) { return value === 2; });

The .some() function returns true if the callback returns true for any element. (The function returns as soon as the callback does return true, so it doesn't bother looking beyond the first match.)

You can usually use the .reduce() function as a more general iteration mechanism. If you wanted to count how many instances of 2 were in your array for example:

 var twos = a.reduce(function(c, v) { if (v === 2) c += 1; return c; }, 0);
like image 28
Pointy Avatar answered Oct 05 '22 11:10

Pointy


Others have mentioned .indexOf() and .some(). I thought I would add that a good old fashioned for loop gives you the absolute most iteration control because you control the iteration and your processing code is not embedded in a callback function.

While .indexOf() already does exactly what you need, this code just shows how you can directly return when using the old fashioned for loop. It is somehow out of favor these days, but is often still the best choice for better looping control.

function fn(array) {
  for (var i = 0, len = array.length; i < len; i++) {
    if (array[i] === 2) return false;
  }
  return true;
}

Using the for loop, you can iterate backwards (useful when removing items from the array during the iteration), you can insert items and correct the iteration index, you can immediately return, you can skip indexes, etc...

like image 30
jfriend00 Avatar answered Oct 05 '22 12:10

jfriend00