Using JavaScript To Loop ➿ Through an Array using forEach and Lodash forEach() & jQuery each() Methods to Iterate Over Arrays and Objects

javascript-for-loopsOne of the most fundamental programming constructs is the for loop. All languages have some implementation of for each and JavaScript is no different.

As the language has matured so have our options to loop over arrays and objects. JavaScript objects are also arrays, which makes for a clean solution to index values by a key or name.

The Basic For Loop

JavaScript for loops iterate over each item in an array. JavaScript arrays are zero based, which means the first item is referenced with an index of 0.

Referencing items in arrays is done with a numeric index, starting at zero and ending with the array length minus 1. The syntax to access an array member

The following is an example of using JavaScript to loop through an array.


let myArray = ["one", "two", "three", "four"];

for(let i = 0; i < myArray.length; i++){

   console.log(myArray[i]);

}

/* Outputs:
one
two
three
four
*/

If you need to iterate through a second level property or field you can nest for loops. The biggest thing you need to keep track of is declaring a separate index variable.


let myArray = [{"child": ["one", "two", "three", "four"]}, 
               {"child": ["five", "six", "seven", "eight"]}];

for(let i = 0; i < myArray.length; i++){

   let childArray = myArray[i].child;

   for(let j = 0; j < childArray.length; j++){

  console.log(childArray[j]);

   }

}

/* Outputs:

one
two
three
four
five
six
seven
eight
*/

The JavaScript Array forEach Method

The traditional for loop is easy to understand, but sometimes the syntax can be tedious. For example the nested loop requires new variable declarations with a nested scope. Modern JavaScript has added a forEach method to the native array object.

This method is a member of the array prototype and uses a callback function for you to embed any custom logic to the iteration.

The forEach callback function actually accepts three arguments:

  • element value
  • element index
  • array being traversed (has anyone ever used this???)

The element is the current item's value. Think of it as myArray[i]. The next value is the index, which would correlate to i in the previous examples.

The last parameter is a copy of the array being itereated through. I can see how this could be useful, but often I see it ignored. This is a nice to have, not something you need to worry about.

If you don't declare a variable for any of these parameters they just wont be allocated. For example, most uses of the forEach method just use the element, and ignore the index and array. The element is the most important value when iterating, so you should always declare an element parameter.



myArray.forEach(function(element) {
  console.log(element);
});

/* outputs:
one
two
three
four
*/

If you want to count, you need to declare a variable outside the method's scope.


let count = 0;

myArray.forEach(function(element, i) {
  count++;
});

console.log("forEach processed: ", count, " elements.");

// forEach processed:  4  elements.

forEach only works on arrays, which means you need to be a little creative if you want to iterate over objects.

A common scenario I run into is looping over element list returned from document.querySelectorAll. Instead of returning an array of matched elements, it returns a node list.

A node list is not an array, but an enumeration object, containing each of the matched elements. This means the forEach method is not available. You can still iterate over the list using a traditional for loop or accessing an element directly using array index notation, elements[index].

But a utility method might be a better way.

Lodash forEach() to Iterate over Objects

Never fear, Lodash is here!

Lodash is a JavaScript utility library that can reduce your code size and quality through its many functions. Lodash has a helpful iteration methods, such as forEach and map that work on objects as well as arrays.


_.forEach(arr, function(element, i) {
  console.log(element);
});

forEach is included in the Lodash Core build, a small (4kb) size library that includes the most common methods used. The forEach method is also aliased to the each method.

This is great when you want to loop through the list in order. But what do you do when you want to loop from the bottom of the list, in reverse order?

Lodash has a sibling method, forEachRight. This method starts at the end or right of the list and loops in reverse order.


_.forEachRight([1, 2], function(value) {
  console.log(value);
});
// => Logs 2 then 1.

I like Lodash, especially when writing node modules. It has so many useful methods and its documentation is a progressive web app!

The Old School jQuery each() Method

jQuery, like Lodash, includes a generic iterator method, each. It has two parameters, an array and a callback method.

The callback method has two values passed to it, the current index and the item value, which is the opposite of the array and Lodash forEach methods. The callback method is executed against each item in the array.


$.each(myArray, function( index, value ) {
  console.log( index + ": " + value );
});

If you pass an object instead of an array the function loops over the object's properties, using the name as a key.

This makes sense if you understand each JavaScript object is an associative array. When you think about a JavaScript in terms of an associative array the index is the member name.

obj["property-name"]

This returns a reference to the value, which could be a traditional value, function, array or a child object.

I love associative arrays because they make JavaScript super flexible. I can't tell you how many projects I have needed an array I can quickly reference by a name, not a numeric index. These have come in handy many times.

The jQuery each method makes it easy to iterate over objects using the associative syntax.


var obj = {
  "flammable": "inflammable",
  "duh": "no duh"
};
$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});

But you don't need jQuery to use this technique!

Iterating Over a JavaScript Associative Array

I used this technique in my Single Page App Router. When I composed my SPA's routes I would use the route slug as the index and the value the view's object.

I remember reading about Netflix dealing with memory leaks in the Express routing engine several years ago. The problem they encountered was due to the route engine using traditional arrays to manage routes.

They experienced memory leaks because they update the site hundreds if not thousands of times a day. Each time an update was published the updated page data was added to the express route table.

Unfortunately, due to it being a simple array duplicate routes were added. The amount of overhead to keep the route table clean was heavy.

This story caused me to review how I handled my SPA routes. Fortunately I could not have this problem because I was using associative arrays.


   if (routes.hasOwnProperty(slug)) {

   return routes[slug];

  }
 
    for (key in routes) {

     if (routes.hasOwnProperty(key)) {

      route = routes[key];

      //do more here
    }

   }

This is just one example of how I have used JavaScript object properties as an array index. I have found this technique usefule in many situations.

Summary

Looping over arrays is a fundamental language construct. JavaScript has several native ways to iterate an array. Utility libraries like Lodash and jQuery also have helpful methods to make traversing array and object values easy to manage.

Your challenge to is find the technique that works best for your situation.

Share This Article With Your Friends!