14

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?

Neuron
  • 5,141
  • 5
  • 38
  • 59
four-eyes
  • 10,740
  • 29
  • 111
  • 220

3 Answers3

15

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

Timus
  • 10,974
  • 5
  • 14
  • 28
Pascal Nitcheu
  • 667
  • 7
  • 8
13

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

Neuron
  • 5,141
  • 5
  • 38
  • 59
  • Hm... So I would have to change all the `maps` into `for-loops`? – four-eyes Oct 30 '17 at 14:26
  • 1
    yes. i also added that in my answer, but the map function is not meant for iteration. it actually returns a new array and shouldn't be used for anything but that. – Neuron Oct 30 '17 at 14:31
  • Would it work if I wrap the `map` inside the `for-loop`? – four-eyes Oct 30 '17 at 14:52
  • 1
    you are fighting the symptom, not the problem. the `map` function is not meant to be used to loop over the data. don't use it for that! if you are not storing the result of `map` in a variable you are not using it correctly – Neuron Oct 30 '17 at 14:56
  • Hm, shouldnt make that much of a difference if I let the result of `map` disappear in the `void` I assume?! – four-eyes Oct 30 '17 at 15:01
  • there are two reasons why you shouldn't do it that way. first: blantly put this is more expensive on the hardware, as you create an arrow function expression and there is some array created in the background which gets readied for return. secondly: this is not best practice. There are always many ways to your goal in programming, but usually you'll write code in your professional life which get looked at and serviced by other people. using the "correct" way will make it easier for them to instantly understand your intuition and understand your code quicker. – Neuron Oct 30 '17 at 15:09
11

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

Victor
  • 3,669
  • 3
  • 37
  • 42