Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot break for-loop: Unsyntactic break

Tags:

javascript

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?

like image 508
Stophface Avatar asked Oct 30 '17 14:10

Stophface


People also ask

How do you skip a loop in JavaScript?

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.

How do you break a loop in TypeScript?

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.

Can we break for of loop?

Using break as well as continue in a for loop is perfectly fine. It simplifies the code and improves its readability. Yes..


Video Answer


2 Answers

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

like image 165
Максим Погребняк Avatar answered Sep 23 '22 03:09

Максим Погребняк


To fix this problem you can simply use return; instead of break;

like image 36
Pascal Nitcheu Avatar answered Sep 23 '22 03:09

Pascal Nitcheu