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.