Wednesday, April 1, 2015

At a glance it looks like break; is the way to wiggle out of a foreach loop in JavaScript once you've found what you want.

This suggested it. I woke this morning thinking about the pain of the inability to return out of a foreach loop as detailed here. In my example, I find what I want, tuck into a variable to return later, and then finish looping... but I shouldn't have to finishing looping. Duh.

 
 

Addendum 1/4/2017: What's above is really terrible! There is no early escape form a .forEach in JavaScript. At best, you may minimize how "heavy" the looping is after a certain point if you want to do a little dance.

var whatever = function() {
   var message = "No records were found.";
   var isToKeepGoing = true;
   this.columns.forEach(function (column) {
      if (isToKeepGoing) {
         if (column.expandableRow) {
            isToKeepGoing = false;
            if (column.expandableRowEmptyError) {
               message = column.expandableRowEmptyError;
            }
         }
      }
   });
   return message;
};

No comments:

Post a Comment