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?