When it comes to writing jQuery-based JavaScript, there are generally two camps of people:

  • Those who believe that you should intermingle jQuery with vanilla JavaScript for when you need it
  • Those who believe that if you’re importing jQuery, then you should use it as much as possible

Both camps have their own sets of arguments neither of which I’m looking to explore in this particular post; however, one of the features that’s all too common is having to loop through a vanilla array using JavaScript.

The two main ways that you can do about doing this are to use a standard for, while, or do loop or use jQuery’s iterator.

If you fall into the former camp, but are looking to use an iterator, here’s how you can begin looping through an array with jQuery.

First, define the array:

var myArray = [ 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten' ];

In vanilla JavaScript, you may do something like this:

var i, currentElem;
for( i = 0, l = myArray.length; i < l; i++ ) {
	
	currentElem = myArray[i];
	// Do work with the current element
	
}

If the collection was initializing using jQuery then we’d originally do something this like:

var $currentElem;
$(myArray).each(function() {
	
	$currentElem = $(this);
	// Do work with the current element
	
});

But since the array is a collection defined used vanilla JavaScript, then we have to setup the iterator in a slightly different manner:

$.each( myArray, function( intValue, currentElement ) {
	// Do work with currentElement	
});

Basically, you still leverage the each function, but you first pass it a reference to the vanilla array and then you pass it a callback function to use when iterating through the array.

The callback’s first argument is the index of the array, the second argument is the element itself.

Easy enough, right? Even still, it surprises me not only how much I’ve needed to use this when working with other projects, but how often I’ve heard this question crop up.

Category:
Notes
Tags:

Join the conversation! 2 Comments

  1. I’ve used JQuery to loop through an array with an iterator, but then a colleague with more JavaScript experience said that with larger arrays it’s actually more performent to use the plain old JavaScript for loop. Thoughts?

    • I agree with your colleague. The most optimal form would be like this:

      var i, l;
      for( i = 0, l = arr.length; i < l; i++) {
      // Do work
      }

      This way, the length is only checked once and stored rather than checking it every time an iteration occurs. Unless things have changed, this is the fastest way to iterate through an array in vanilla JavaScript.

      That said, it’d have to be a really large data set before you’d start to truly “feel” the performance hit.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.