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?

3
  • 2
    I guess you want to break out of the map function. You can't do that. Commented Dec 7, 2016 at 7:18
  • 1
    May be stackoverflow.com/questions/12260529/… Commented Dec 7, 2016 at 7:23
  • Use the right tool for the job. You want find, not map. Commented Dec 7, 2016 at 7:56

1 Answer 1

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(); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.