Somenath Sinha Somenath Sinha - 1 year ago 44
jQuery Question

How does this function obtain the index value?

I went through a code snippet, and this anonymous function is passed the value of index and value as parameters. How is this useful, since we're not manually calling the function at all? (other than via event calls). Further, from where does this index value (which is subsequently used in the function) originate? Who exactly is passing this values, and where do they come from?

var hideCode = function houdini()
var numRand = getRandom(4);
$(".guess_box").each(function(index, value)
if(numRand == index)
$(this).append("<span id='has_discount'></span>");
return false;

Answer Source

From jQuery's docs:

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

What this means is that it after $('.guess_box') is called, the .each(...) iterates over the returned array starting from 0 until length-1. This works very similarly to calling a for-loop on the returned array.