How to break foreach loop in javascript?

19,800

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

Share:
19,800
Rohit Kumar
Author by

Rohit Kumar

Updated on June 24, 2022

Comments

  • Rohit Kumar
    Rohit Kumar almost 2 years

    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.