How to break _.each() function in Underscore.js ? (original) (raw)
Last Updated : 02 Jun, 2020
It is not possible to break the _.each function. The reason is that the _.each function works similarly to the forEach function and imitates its native behavior. It does not allow us to break the loop or escape from it except by throwing an exception. However, one can use different methods like:
- Throw Exception
- _.find() function
- _.some() function
Throw Exception: One can throw an exception from each on getting the desired value.
Syntax:
try { _(arrayName).each(function(elementName){ // your code with condition where // exception is to be thrown }) } catch(exception){ // dont do anything here }
Example:
<script>
`` var
arr = [10, 20, 30, 40];
`` var
cnt = 0;
`` try
{
`` _(arr).each(
function
(value) {
`` if
(value == 30) {
`` throw
new
Error();
`` }
`` console.log(cnt++);
`` })
`` }
`` catch
(e) {
`` }
</script>
Output:
0 1
Here exception is thrown when the value 30 is detected. Otherwise the count (cnt) is incremented by 1
_.find() Function: The _.find() function can be used to break the loop when the required value is found. The result can be stored in an external variable.
_.find(arayName, function(elementName){ if(elementName == value){ return false; } // Write your own code }
Example:
<script>
`` var
arr = [10, 20, 30, 40];
`` var
cnt = 0;
`` _.find(arr,
function
(value) {
`` if
(value == 30) {
`` return
false
;
`` }
`` console.log(cnt++);
`` });
</script>
Output:
0 1
Here the _.find() function returns false when the value 30 is reached. Otherwise the count (cnt) is incremented by 1
Note: One can also include the finally block after the catch block.
_.some() Function: The _.some() function is similar to the _.find() function and stops traversing the list once the required value is detected. Result can be stored in an external variable.
Syntax:
_.some(arayName, function(elementName){ if(elementName==value){ return false; }
// Write your own code
}
Example:
<script>
`` var
arr = [10, 20, 30, 40];
`` var
cnt = 0;
`` _.some(arr,
function
(value) {
`` if
(value == 30) {
`` return
false
;
`` }
`` console.log(cnt++);
`` });
</script>
Output:
0 1
Here the _.some() function returns false when the value 30 is detected. Otherwise the count (cnt) is incremented by 1.