311 Views
Passing a function as an argument to other functions is a difficult concept to understand for beginners, especially those coming from other languages. D3 further compounds this difficulty by making the functions-as-arguments model integral to the basic pattern, but doesn’t force the designer to understand what the heck is going on when they type function in the middle of their code. Instead of learning what the underlying code is doing, some just blindly type… // figure 4.1 // ... .append('rect') .attr('fill', function(d,i){ return 'brown' }) .attr('stroke', function(d,i){ return 'none' }) …even when it clearly isn’t necessary. I swear code that looks like this is written every day by beginner and intermediate d3 designers because, while it doesn’t explicitly blow up their code, it still works. It runs. This article will try to make sure it doesn’t happen again. We will cover what d3 is doing when you pass a function instead of a value. By the end you will have a better understanding of a wonderfully useful part of javascript.