- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to terminate javascript forEach()?
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. }
- Related Articles
- How to terminate a MongoDB shell script earlier?
- How to make a list of partial sums using forEach JavaScript
- How to show a foreach loop using a flow chart in JavaScript?’
- How to apply forEach tag in JSP?
- Terminate the timer in Java
- How do I terminate a thread in C++11?
- How to terminate/destroy a process using Process API in Java 9?
- What is the use of forEach() method in JavaScript?
- How to use PowerShell break statement in foreach loop?
- How to use PSCustomObject in PowerShell foreach parallel loop?
- How to use the foreach loop parallelly in PowerShell?
- How to use ForEach-Object Parallel cmdlet in PowerShell?
- What is difference between forEach() and map() method in JavaScript?
- Is it possible to change values of the array when doing foreach() in javascript?
- How to use a variable inside a Foreach-Object Parallel?

Advertisements