Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript foreach return [duplicate]

Tags:

I wonder if there is a better way of doing this - looks like returning out of a foreach doesn't return out of the function containing the foreach loop, which may be an expectation from C# devs.

Just wondering if there is a cleaner way of doing this:

example() {     var forEachReturned;      this.items.forEach(item => {         if (true) {             forEachReturned = true;             return;         }     });      if (forEachReturned) {         return;     }      // Do stuff in case forEach has not returned } 
like image 274
Ross Avatar asked Aug 16 '18 09:08

Ross


1 Answers

The cleaner way would be to not use .forEach. It's almost never needed if you're using TypeScript or a modern version of JavaScript:

example() {     for (let item of this.items) {         if (item === 3) {             return;         }     }            // Do stuff in case forEach has not returned } 

If the code inside your loop doesn't have any side-effects and you're just checking for a condition on each item, you could also use a functional approach with .some:

example() {     if (this.items.some(item => item === 3)) {         return;     }      // Do stuff in case we have not returned } 
like image 112
JLRishe Avatar answered Sep 20 '22 13:09

JLRishe