views:

94

answers:

4

Various JavaScript libraries (e.g. jQuery) offer an each method:

$.each(myObj, myFunc);

What's the advantage over using the built-in for..in loop:

for(var i in myObj) {
    myFunc(i, myObj[i]);
}

In both cases I'd have to check for unwanted properties (usually functions), so I don't see why the each method is provided in the first place.

+3  A: 

As the jQuery $.each(object, callback) explanation states

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.

In keeping in line with other utility functions, it provides an easy one line jQuery-fied syntax to use

Russ Cam
But `for[ each]..in` loops can be used on both `{}` and `[]` as well!?I guess I'll stick to the built-ins unless I have a specific need for `each`'s capabilities.
AnC
I think one could make a similar argument for other utility functions like $.isFunction - why use the jQuery implementation when you could easily do the check yourself? The whole idea is to provide an intuitive and meaningful interface, consistent across the library
Russ Cam
+2  A: 

In the each example, you can use this to call the currently selected element and work with it.

$("div img").each(function(i){
    this.id = this.id + "_" + i;
});
Ólafur Waage
Sorry, I meant the jQuery utility function, not the object method.
AnC
+2  A: 

The first takes 1 line, the other takes 3. You can do things like chaining, so you could call another array function after the first is done.

AgileJon
It's worth nothing that the former is more complicated in that it requires a callback...Chaining is a good point, though that depends on the context.
AnC
chaining is definitely a primary advantage afaics, performance being the primary drawback
annakata
+3  A: 

I can think of at least 3 advantages, though they are relatively small.

  1. It follows the jQuery chainability paradigm, allowing you to chain multiple iterations together if needed.
  2. It breaks out both the key and the value for you as arguments to the callback, removing this code from your loop.
  3. The syntax is consistent with other jQuery code you may have, potentially increasing readability.

The disadvantages are some, small overhead -- you have to pay for what it does for you -- and the potential for confusing it with the $().each() method which is completely different.

tvanfosson
Thanks, that's what I figured; it's essentially syntactic sugar without any enhanced capabilities - which is fine, of course, but it means that I'll stick to the built-in for..each loops for most cases.
AnC