5

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.

8
  • 2
    instead of a break use a return You can not technically break out of forEach, use a for otherwise. Commented Aug 30, 2017 at 18:11
  • 1
    There is no way to stop or break a forEach() loop other than by throwing an exception. Commented Aug 30, 2017 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. Commented Aug 30, 2017 at 18:12
  • 1
    You should refer this question, here it is explained in detail - stackoverflow.com/questions/6260756/… Commented Aug 30, 2017 at 18:12
  • 2
    Side note for your future understanding... There's no actual loop in your code. That's a function call. Commented Aug 30, 2017 at 18:12

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.