Which is best "for loop" or "$.each" function in jQuery?Explain Why?

Forums jQueryWhich is best "for loop" or "$.each" function in jQuery?Explain Why?
Staff asked 3 years ago

Answers (2)

Add Answer
Staff answered 3 years ago

The ‘FOR’ loop being a native Javascript function is undoubtedly faster, however, the scope is all the same, so in some cases, the .each() method would be preferable, as each iteration is its own scope and in some cases, For loop will be preferable.

  • jQuery.each:
  1. Fits well in jQuery code (in chaining and style).
  2. No worries about scope (references to the iterator and object will be persistent).
  3. Can be used universally (for all kinds of objects and iterating over object keys).
  • for-loop:
  1. High performance (for large datasets).
  2. Full control over iterator (skip items, splice items from the list, etc.).
  3. The for-loop will always work, for there is no dependency on jQuery.
  4. Same familiar syntax as most other similar languages.
Staff answered 3 years ago

In this example,

  • $.each() is a jQuery function being executed which will be used to iterate over your list, so the overhead should be the jQuery function as well as the overhead of calling for that function for every item in the list.
  • for() In this case, there is no overhead at all, except looking up the length of the list on each iteration.

You should prefer for loop for fast performance

Subscribe

Select Categories