student student - 4 months ago 10
jQuery Question

What is the concept behind javascript parameters?


Let me try to explain my weird confusion


I'm trying to learn about
d3.js
. I'm seeing a lot of functions with some odd kind of parameters (they look odd at least to me).

d3.selectAll("p").style("color", function(d, i) {
return i % 2 ? "#fff" : "#eee";
});



  • What is
    d
    doing here? Why is it passed when it's of no use?

  • From where
    i
    (along with value) is getting passed?



Also I was following Jan's tutorial and built a fiddle. This also has some odd function params:



.attr("cy", function(d) {
return y(d.y)
})





.delay(function(d, i) {
return i * del(Math.random())
})




  • From where
    d
    (along with value) is getting passed?


Answer

What is d doing here? Why is it passed when it's of no use?

The style function will call the callback with a specific set of arguments. The fact that the callback doesn't happen to need the first of those arguments doesn't change how style will call it. So the callback has to accept the argument, but then ignore it.

From where i (along with value) is getting passed?

The style function. It's what calls the callback, so it's what determines the values of the arguments the callback receives.

Here's an example of a function accepting and calling a callback, which will probably help clarify things. See the comments:

// Here's our function that accepts a callback, just like
// d3's `style` accepts a callback.
function doSomething(callback) {
  // Call the callback with two arguments,
  // a random letter and a random number:
  var letter = String.fromCharCode(65 + Math.floor(26 * Math.random()));
  var number = Math.floor(Math.random() * 100);
  callback(letter, number);
}

// Now we call that function, giving it a callback
// that makes use of both of its arguments:
doSomething(function(l, n) {
  console.log("First callback: The letter is: " + l);
  console.log("First callback: The number is: " + n);
});

// Now we call that function, giving it a callback
// that only uses the second argument:
doSomething(function(l, n) {
  console.log("Second callback: The number is: " + n);
});