![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 break the _.each function in underscore.js
You can't break from each method. It copies the native forEach method's behavior and the native forEach doesn't provide to escape the loop (other than throwing an exception).
You can use other functions like −
_.find: it breaks out of the loop when the element is found. For 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 each. For example,
try { _([1, 2, 3, 4]).each((element) => { // Check your condition here if (element === 2) { throw new Error(); } // Do what you want with the elements here // ... }) } catch (e) { // Do nothing. }
Advertisements