Search code examples
javascriptarraysforeachreturn

Return value for function instead of inner function in Array.forEach


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?


Solution

  • 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;
        });
    }