TypeScript – How to break forEach?

Really? Do you want to do that?

So basically, you cannot use break, continue, return statements inside a forEach because it is like an callback function, which behaves like an normal function. But,

Never stop until you find a solution

I just found out three ways of doing it,

  • The ugly way
  • The Controversial way
  • The fun way

The ugly way

Use for instead of forEach where you can use break,continue, return statements.

INPUT:
var names = ["test","dev","qa"];
for (var i = 0; i < names.length; ++i) {
    if (names[i] == "dev") {
        break;
    }
    console.log(names[i]);
}

OUTPUT:
test

The Controversial way

You can use try-catch where you can surround your whole code with try-catch and if you want break inside a forEach, just throw an exception.

I know this is bad, but this is a way of doing it.

INPUT:
var names = ["test","dev","qa"];
try{
    names.forEach(name => {
        if(name === "dev"){
            throw new Exception("aa");
        }
        console.log(name);
    });
}
catch{
    console.log("Outside forEach..");
}

OUTPUT:
test
Outside forEach..

The fun Way

You can make use of every() function. But it will not iterate like forEach.

INPUT:
var names = ["test", "dev", "qa"];
names.every(name => {
    if (name === "qa") {
        return;
    }
    console.log(name);
});

OUTPUT:
test

If you want to have the same iteration functionality like forEach you can use some() function.

INPUT:
var names = ["test", "dev", "qa"];
names.some(name => {
    if (name === "qa") {
        return;
    }
    console.log(name);
});

OUTPUT:
test
dev

Conclusion

I prefer the fun way, because it’s the same thing using break statement. And if you find any other ways of doing it, please share it in the comments.

Happy Coding!

Cheers! 🙂

One thought on “TypeScript – How to break forEach?

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: