Search code examples
javascriptarraysd3.jsdata-bindinganonymous-function

Anonymous function and data binding mechanism explanation on example of D3.js implementation


My question is about the work with D3.js visualization JavaScript library.

I have an array of objects, each object contains the same properties, but with the different numeric values. Now, I want to find the maximum value of the specific property among the objects of this array.

Here is the JavaScript code, which does it:

d3.max(parsedCSV, function (d) {
    return d["AverageGrade"]
})

This code finds the maximum value of AverageGrade property among all, let say, students, which are stored in the parsedCSV array. It works as I need.

According to the d3.max() reference, this function gets array and returns its maximum value. What I don't understand is the part with the anonymous function call:

function (d) { return d["AverageGrade"] }

Can you, please, elaborate, how exactly does it work, how the data is bonded and what is the technical/professional name of this approach?


Solution

  • This is called a callback function, and it basically provides a reference to a function that is called at each iteration of the array that you passed as the first parameter. It is a very common pattern in JavaScript, and many libraries work based on this. For example, I assume you used d3.csv to get a parsed csv, and provided an anonymous function as the second parameter. This is exactly the same idea here. If you work with d3, you will encounter this everywhere (e.g. using the enter-update-delete pattern, or using events).

    FYI, in the case of d3, you can use a second parameter (generally noted i), that holds the index of the item in the collection.