JavaScript - how to exit early from a loop

JavaScript - how to exit early from a loop

In JavaScript, there are many ways to build a looping statement, in such a way that it can exit early.

Here are a few examples:

Built-in function 'some'
ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some

 var findInArray = function (text, array) {  
   var found = false;  
   array.some(function(item) {  
     if(item === text) {  
       found = true;  
       return true; //early exit  
     }  
     return false; //continue (not strictly needed, but good for consistency)  
   });  
   return found;  
 };  

jQuery.each()
ref: http://api.jquery.com/each/

 var findInArray = function (text, array) {  
   var found = false;  
   $.each(array, function(item) {  
     if(item === text) {  
       found = true;  
       return false; //early exit  
     }  
     return true; //continue (not strictly needed, but good for consistency)  
   });  
   return found;  
 };  

for loop

 var findInArray = function (text, array) {  
   var found = false;  
      for(var i = 0; i < array.length; i++) {  
     if(item === text) {  
       found = true;  
       break; //early exit  
     }  
     //continue  
   });  
   return found;  
 };  


other ways...

Other ways, including a while() loop
note: the built-in function 'forEach' is NOT suitable for exiting early.


Comments