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.
1 Answer
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.
15 Comments
guradio
can you elaborate more on the answer. this one is not clear this is more like a comment
BotNet
@guradio if you chill out the answer will be updated ;)
Pranav C Balan
yup that may be a reason, so the value arg doesn't have that much importance here :)
guradio
i was too excited to know mate :)
BotNet
@guradio that sounded more snappy than intended, I've had a couple drinks and am laughing
|
$.mapand$.fn.mapcallbacks.$.mapfirst argument is value... i didn't noticed that :)