2

I am using this code to check if something is valid

function isValid(source, target) {
  arr.forEach(function (el) {
    if (el.value === 3) {
      return false;
    }
  });

  return true;
}

The problem is that the return false line of code will only terminate the inner function in forEach and not the entire isValid function.

How do I terminate the outer function?

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • Wouldn't it be easier to use a "normal" for loop for this? – UnholySheep Oct 05 '16 at 07:58
  • 3
    Use [`some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) or [`every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every). – Sebastian Simon Oct 05 '16 at 07:58

3 Answers3

2

Use Array#every for checking the elements

function isValid(source, target) {
    return arr.every(function (el) {
        return el.value !== 3;
    });
}

The same with Array#some

function isValid(source, target) {
    return !arr.some(function (el) {
        return el.value === 3;
    });
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can't.

See the documentation from MDN:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Will be good to use regular for in, but with forEach you can do:

function isValid(source, target) {
  var r = true;
  arr.forEach(function (el) {
    if (el.value === 3) {
      r = false;
      return false; // terminate loop
    }
  });

  return r;
}
Taron Saribekyan
  • 1,360
  • 7
  • 13