Using jQuery’s Each method to iterate through a JavaScript array

The Each method in jQuery is pretty useful and can be used to iterate through the elements within a jQuery object.

I’ve been using it recently to iterate through JavaScript arrays.  It saves having to use a for loop and the code looks nicer.

Say I have the following code that creates an array and outputs the values using a for loop.

var names = ['Joe', 'Emily', 'Tom', 'Sylvain'];

for (var i = 0; i <= names.length - 1; i++) {
    alert(i + ':' + names[i]);

I can achieve the same result using the Each method as follows.

var names = ['Joe', 'Emily', 'Tom', 'Sylvain'];

$.each(names, function(index, value) {
    alert(index + ':' + value);

The Each method accepts two parameters, the first is the object to iterate and the second is the callback function that will be called for each item.

The callback function allows two parameters; the index of the array (or key if we’re iterating over objects), and the value itself.

In the above example I’m simply displaying the index and value to the user.

Posted on by Joe in JavaScript, jQuery

Add a Comment