Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript D3.js Data Binding with D3.js Data Binding

Rafael Moreno
Rafael Moreno
17,642 Points

Who passes in "d" in function(d)?

in data.attr('r', function(d)).... I understand that "d" is the data and that you can access certain parts of it with the dot notdation, but who calls the function and passes in "data" as the value for "d"? right now it seems that it just magically happens and that the program knows "d" is "data" without it being explicitly called.

1 Answer

Samuel Webb
Samuel Webb
25,370 Points

I would suggest reading the D3 API documentation at: https://github.com/mbostock/d3/blob/master/d3.js ... Pay special attention to d3_selectionPrototype.attr and d3_selection_attr.

The short answer is that you're just passing in a function that takes an argument, and the function you're creating does something with that argument. You can name the argument whatever you want, but in this instance you're calling it d. Then that function is passed into the data.attr() method which calls the passed in function, passing the data into the function using the d as the variable.

Here's a short example of how something similar works:

function person(name, fn) {
  fn(name);
}

person('Sam', function(n){
  console.log('Hello ' + n);
});

// This will log:
// Hello Sam

The subject your question is about is Callback Functions. To get a deeper understanding of how they work, here are a few resources you can take a look at:

Samuel Webb
Samuel Webb
25,370 Points

No problem. Glad to help.

Sergey Scherbo
Sergey Scherbo
5,784 Points

Hello! I think it's easy to understand if u declare your CB function, instead just passing it as a parameter. And it also makes your code easy to read, in my opinion.

function person (name, fn) {
   fn (name);
}

function callback (n) {
   console.log ('Hello ' + n);
}

person ('Sam', callback);