
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Terminate JavaScript forEach Loop
You can't break from the forEach method and it doesn't provide to escape the loop (other than throwing an exception).
You can use other functions like _.find from lodash instead −
_.find − it breaks out of the loop when the element is found. For example,
Example
_.find([1, 2, 3, 4], (element) => { // Check your condition here if (element === 2) { return true; } // Do what you want with the elements here // ... });
Throw an exception from forEach. For example,
Example
try { [1, 2, 3, 4].forEach((element) => { // Check your condition here if (element === 2) { throw new Error(); } // Do what you want with the elements here // ... }) } catch (e) { // Do nothing. }
Advertisements