I want to break
a for-loop
when a certain condition is met
Object.keys(s).map(uk => {
Object.keys(s[uk]).map(ik => {
for (let i = 1; i < data.length; i++) {
if (...) {
s[uk][ik].map(elem => {
if (...) {
if (...) {
data.push(...);
break;
...
However, the break
statement gives me a
Unsyntactic break
Why is that? Its only supposed to break
the for-loop
, or does JavaScript
think that I want to break the map
?
The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch.
To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection.
Using break as well as continue in a for loop is perfectly fine. It simplifies the code and improves its readability. Yes..
You can't use break
with methods like map
, reduce
, forEach
, etc.
But you can .filter
your data before or just .find
the element you need
To fix this problem you can simply use
return;
instead of break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With