0

For example:

function foo() {
  someArray.map(bar) { 
    if (whatever)
      return; // I want to return from the foo function
    return bar.something // Here I return to map function
  }
}

Here is my current solution:

 let flag = false
 function foo() {
   someArray.map(bar) { 
     if (whatever){
       flag = true
     }
     return bar.something // Here I return to map function
   }
 }
 if (flag === true) {
   return;
 }

I'm wondering if there is a better way?

1 Answers1

0

You can't break your map function. But you don't use results of map. If you want to break your map after any condition you can use some array method instead of it.

For example:

let flag = false;
function foo() {
   someArray.some(bar) { 
     if (!whatever){
         return false;
     }
     flag = true;
     return true;
   }
 }
 if (flag === true) {
   return;
 }

Or you can call any function inside some instead of using flag variable

function foo() {
   someArray.some(bar) { 
     if (!whatever){
         return false;
     }
     callYourCodeHere()
     return true;
   }
 }

Or something like this:

function foo() {
   const anySuccess = someArray.some(bar) { 
     return !!whatever;
   }
   if(anySuccess) {
       callYourCodeHere();
   }
 }
Antonio
  • 901
  • 5
  • 12