four-eyes
four-eyes

Reputation: 12394

Cannot break for-loop: Unsyntactic break

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?

Upvotes: 15

Views: 50303

Answers (3)

Pascal Nitcheu
Pascal Nitcheu

Reputation: 799

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

Upvotes: 17

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

Upvotes: 12

Neuron
Neuron

Reputation: 5831

Like you yourself suggested, you are still in the map part. That is actually an arrow function expression and you are no longer in in the loop. Think of it as some function you defined elsewhere, but it's a quicker way of calling that function.

You are not using the map function as it is meant to be used in javascript. It isn't meant to be a convenient way to iterate over an array, but rather create a new array from some other array. You should change your usage of map to some form of a loop

Upvotes: 13

Related Questions