AnC
AnC

Reputation: 4211

advantage of $.each method over for..in loops?

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.

Upvotes: 0

Views: 309

Answers (4)

tvanfosson
tvanfosson

Reputation: 532765

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.

Upvotes: 4

Russ Cam
Russ Cam

Reputation: 125538

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

Upvotes: 4

AgileJon
AgileJon

Reputation: 53626

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.

Upvotes: 2

Ólafur Waage
Ólafur Waage

Reputation: 70041

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;
});

Upvotes: 2

Related Questions