How to do break from a forEach loop JavaScript?

There is no way to stop or break a forEach() loop. We can stop or break it by throwing an exception. Following is an example of doing stop or break inside forEach:

   const carBrand = ['BMW', 'Audi', 'Toyota', 'Tesla', 'TATA'];
   const breakException = {};

   try {
       carBrand.forEach((item) => {
           console.log(item);
           if (item === 'Audi') throw breakException;
       });
   } catch (e) {
       if (e !== breakException) throw e;
   }
Share