TypeScript foreach return [duplicate]

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
}

Leave a Comment