1

I run in to this scenario a lot and would just like to know if my solution is the best and if there might be something better. Many cases I have a forEach loop, and I want to check if any of the values are incorrect, if they are, end the code (return). Here is what I would do without a loop:

const email = '...';
if (email.isInvalid) return;

In a loop I would do this:

const emailList ['...', '...', '...'];
const emailErrors = [];

emailList.forEach((element) => {
    // if (element.isInvalid) return; // This won't work here, it just ends this loop instance, which is my problem
    if (element.isInvalid) emailErrors.push(element);
});

if (emailErrors.length > 0) return; // This will end the code correctly

Is there any better approach to this idea? Using try, catch or something else?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Paul Kruger
  • 2,094
  • 7
  • 22
  • 49

3 Answers3

0

You can't break from forEach. It will run on every element of the array. You can use some to check if at least one of the items is isInvalid. This will short-circuit once an item with isInvalid = true is found

if (emailList.some(element => element.isInvalid))
  return
adiga
  • 34,372
  • 9
  • 61
  • 83
0

Your forEach execute arrow function for each element and not check its result. I not recommend using try-catch because it is very slow. Try to use for-of with return (or break to not return but only break for loop and continue execution code below for)

function start() {
  const emailList = ['abc@test.com', 'invalid 1', 'invalid 2'];
  const emailErrors = [];

  for(let element of emailList)
  {
    console.log(element);
    if(!/@/.test(element)) return;  // some validation (missing @ char)
  };

}

start();
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

You can use Array​.prototype​.every().

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

function validateEmailList(element) {
  return element.isInvalid;
}

console.log(emailList.every(validateEmailList));
Siddharth Yadav
  • 383
  • 2
  • 9