Breaking Bad (Loops in JavaScript Libraries)

JavaScript Libraries are important (e.g., jQuery, Lo-Dash, Underscore), but in the case of asynchronous loops (`forEach` and `each`) they create a lot of confusion… Lo-Dash is not equal to Underscore, unless a special underscore-compatible version is being used.

It was sort of a surprise for me when I discovered inconsistencies in the most popular JavaScript libraries in how they handle their each and forEach loops. This post compares:

  • forEach Loop in Native JavaScript
  • each Loop in Lo-Dash
  • each Loop in jQuery
  • each Loop in Underscore.js
  • forEach Loop in Underscore.js

forEach Loop in Native JavaScript

JavaScript Libraries are important (e.g., jQuery, Lo-Dash, Underscore), but in the case of functional loops (forEach and each) they create a lot of confusion (for loop can be broken with ‘break’). Let’s inspect the example of native JavaScript code for the forEach method:

[1,2].forEach(function(v){
  alert(v);
  return false;
})

This will display us two alert boxes. Try the native JavaScript code yourself in JSFiddle.

This is an expected behavior in most cases because with each iteration we invoke a new function. Unlike the for (var i=0; i<arr.length; i++) {} code that has no function/iterators.

Continue reading “Breaking Bad (Loops in JavaScript Libraries)”