Pranav C Balan Pranav C Balan - 1 year ago 123
Javascript Question

JQuery and JavaScript methods

In majority of JavaScript method(iterator) callback first argument is element and second is index. But in case of jQuery always second argument is element and first one is index. Why they formatted differently? Is that for avoiding confusion between them, since both contains methods like map, filter, etc. Is there any special meaning behind that? I'm just curious to know.

Answer Source

This is because jQuery relies on this; it doesn't need an element iterator.

  // 'this' refers to unwrapped jQuery selector element; no need for arguments == cleaner code
  var $this = $(this);

In Vanilla JS, iterators rely on the parameters:

[].forEach(function(el, index){
   // 'this' refers to Window object; use the argument

Because jQuery can utilize the scoped element using this, it doesn't really need the arguments. I'd have to look up the history of the library to even see if the element existed as the second argument in earlier versions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download