0

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.

4
  • 1
    No, there isn't. jQuery is a rebel in this case. See arguments of $.map and $.fn.map callbacks. Commented Jun 23, 2016 at 3:11
  • @Vohuman : yup, in case $.map first argument is value... i didn't noticed that :) Commented Jun 23, 2016 at 3:24
  • Because you didn't expect it. This is an inconsistency and a confusing feature. Commented Jun 23, 2016 at 3:31
  • 1
    @Vohuman : yes, you are right.... when I started working in jQuery it's always confused me..... Commented Jun 23, 2016 at 3:33

1 Answer 1

2

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

$('selector').each(function(){
  // '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
   el.querySelector('foo')
});

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.

Sign up to request clarification or add additional context in comments.

15 Comments

can you elaborate more on the answer. this one is not clear this is more like a comment
@guradio if you chill out the answer will be updated ;)
yup that may be a reason, so the value arg doesn't have that much importance here :)
i was too excited to know mate :)
@guradio that sounded more snappy than intended, I've had a couple drinks and am laughing
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.