Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Hilary Lee
Hilary Lee
1,156 Points

Use for loop in jQuery instead of $.each()?

Just wondering if there is any circumstance when writing a for loop would be preferable to using $.each() when iterating over an array/object?

I took the AJAX basics course and saw $.each() being used for iteration when an API returned an array, but in the Angular course the first example uses a for loop where I would think $.each() would be more appropriate. Is there a reason?

3 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

jQuery's $.each() method works with both objects and arrays. You can use a JavaScript for loop to iterate through arrays, and a JavaScript for in loop to iterate through objects.

If you are using jQuery you can use either the $.each() method or a for loop to iterate through an array. I don't believe there's a particular advantage to one technique over the other.

Hi Hilary Lee,

jQuery's .each() is very fast so, performance-wise, you'd be safe picking either one in most situations. A good rule to follow is to use jQuery's each method when you're working with jQuery data like a selector that returns multiple elements.

Here's an example where I have a jQuery object (a bunch of blog post containers) and I'd like to append a note to each.

for loop / jQuery object hybrid:

for(i = 0; i < $(".blog-post").length; i++) { 
  $(".blog-post:eq(" + i  + ")").append("<p>Here's a note</p>");
}

That gets the job done, but it's tough to follow and ignores some of the value provided by jQuery. Let's try a full jQuery example, with .each() as the iterator.

$(".blog-post").each(function() { 
  $(this).append("<p>Here's a note</p>");
});

Much easier to read, and probably even faster!

Both of these examples work just fine, but in this case I would go with jQuery for the code clarity, and abstraction that jQuery has provided.

Konrad Kacprzyk
Konrad Kacprzyk
2,894 Points

is it possible to use for loop instead $.each() in this example?

$(document).ready(function () {
  $.getJSON('../video7/data/rooms.json', function (data) {
    var statusHTML = '<ul class="rooms">';
    $.each(data,function (index, room) {
      if (room.available === true) {
        statusHTML +='<li class="empty">';
      } else {
        statusHTML +='<li class="full">';
      }
      statusHTML += room.room + '</li>';
    });
    statusHTML += '</ul>';
    $('#roomList').html(statusHTML)
  }); // end getJSON
}); // end ready
Dave McFarland
Dave McFarland
Treehouse Teacher

Yes Konrad Kacprzyk you could replace the $.each( ) with a loop. Since the example is jQuery, it made sense in this case to stick with that. But there's no reason you couldn't create a loop that loops through the array (the data variable) and acts on each object in the array in turn.

for (var i = 0; i < data.length; i++) {
   var room = data[i];

continue with the rest of the code in the $.each( ) function.