15

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?

6
  • 2
    That is because break expects a loop. You are calling a function in loop. So break does not detects loop.
    – Rajesh
    Commented Oct 30, 2017 at 14:23
  • 1
    Possible duplicate of How to short circuit Array.forEach like calling break?
    – Rajesh
    Commented Oct 30, 2017 at 14:24
  • @Rajesh I dont want to use for-Each. I am using a for-loop
    – four-eyes
    Commented Oct 30, 2017 at 14:25
  • why don't use Array.some
    – Mirodil
    Commented Oct 30, 2017 at 14:25
  • @Stophface The point of duplicate was, how to break through a function.
    – Rajesh
    Commented Oct 30, 2017 at 14:26

3 Answers 3

16

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

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

6
  • Hm... So I would have to change all the maps into for-loops?
    – four-eyes
    Commented Oct 30, 2017 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
    Commented Oct 30, 2017 at 14:31
  • Would it work if I wrap the map inside the for-loop?
    – four-eyes
    Commented Oct 30, 2017 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
    Commented Oct 30, 2017 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
    Commented Oct 30, 2017 at 15:01
12

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.