4

I have an object mobile_specs which have several fields such as DeviceName, Brand, Camera. I loop though the mobile_specs object so that i can print the specifications of two mobiles in tabular format:

var i=0;
Object.keys(mobile_specs).forEach(function(key) {
                       if(i==5)
                       {
                        break;
                       }
                      var mobile1=mobile_specs.[key];
                      var mobile2=mobile_specs.[key];
                      alert(mobile1 + " " +mobile2);
                      i++;
                });

But the above code give me an error which is:

Illegal break statement

How can i break my loop when i==5 ?

Any help is appreciated.

Rohit Kumar
  • 438
  • 2
  • 6
  • 16
  • 2
    instead of a `break` use a `return` You can not technically break out of `forEach`, use a `for` otherwise. – Get Off My Lawn Aug 30 '17 at 18:11
  • 1
    [There is no way to stop or break a forEach() loop other than by throwing an exception.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) – litelite Aug 30 '17 at 18:11
  • 1
    Note that having a counter in this case does not make much sense, as objects' properties are not ordered. Which means that you may have different first five outputs depending on the engine/browser you're using. – sp00m Aug 30 '17 at 18:12
  • 1
    You should refer this question, here it is explained in detail - https://stackoverflow.com/questions/6260756/how-to-stop-javascript-foreach – Mohit Bajoria Aug 30 '17 at 18:12
  • 2
    Side note for your future understanding... There's no actual *loop* in your code. That's a function call. – David Aug 30 '17 at 18:12
  • 1
    https://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break – Pavan Chandaka Aug 30 '17 at 18:14
  • 1
    instead of starting the forEach, take the values of Object.keys in a variable. Then you can use normal for loop with that variable and there break will work – JEET ADHIKARI Aug 30 '17 at 18:16
  • Thank you @David – Rohit Kumar Aug 30 '17 at 18:16

1 Answers1

8

There is no way to stop or break a forEach() loop other than by throwing an exception. I think forEach is not suited for your job, use a simple loop instead

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
marvel308
  • 10,288
  • 1
  • 21
  • 32