Typescript Foreach Return [Duplicate]

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
}
2

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
}
2
James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest