Q:

Understanding why three nested functions are used in .attrTween

This example from Mike Bostock has been very useful for me. It shows a point flowing endlessy along a curvilinear closed path. The code is very simple, except for the last lines which I don't understand. I write below the relevant code:
transition();

function transition() {
  circle.transition()
      .duration(10000)
      .attrTween("transform", translateAlong(path.node()))
      .each("end", transition);
}

// Returns an attrTween for translating along the specified path element.
function translateAlong(path) {
  var l = path.getTotalLength();
  return function(d, i, a) {
    return function(t) {
      var p = path.getPointAtLength(t * l);
      return "translate(" + p.x + "," + p.y + ")";
    };
  };
}

Why there are three nested functions? I know that the outer function translateAlong should return a function of t (time), but I don't understand the role of the intermediate function(d, i, a). I've only tested that it cannot be omitted, but its arguments can.

A:

We have 3 functions. Let's name their levels:
function translateAlong(path) {//1st level here
  var l = path.getTotalLength();
  return function(d, i, a) {//2nd level here
    return function(t) {//3rd and last level
      var p = path.getPointAtLength(t * l);
      return "translate(" + p.x + "," + p.y + ")";
    };
  };
}

For answering your question, it's very important to understand that this...
.attrTween("transform", translateAlong(path.node()))

... will call translateAlong immediately and get its return value. Which is this:
function(d, i, a) {//2nd level here
    return function(t) {//3rd and last level
      var p = path.getPointAtLength(t * l);
      return "translate(" + p.x + "," + p.y + ")";
    };
};

Now, let's go to the D3 v3 API (the version in your link). It says:

transition.attrTween(name, tween)
Transitions the value of the attribute with the specified name according to the specified tween function. The starting and ending value of the transition are determined by tween; the tween function is invoked when the transition starts on each element, being passed the current datum d, the current index i and the current attribute value a, with the this context as the current DOM element. (emphasis mine)

As you can see by the parameters' names in the section I put in bold (even if Bostock never uses them, which explains your correct observation that "its arguments can [be omitted]"), the tween function is exactly the function you're asking about:
return function(d, i, a) {//this is the tween
    return function(t) {
      var p = path.getPointAtLength(t * l);
      return "translate(" + p.x + "," + p.y + ")";
    };
};

It's worth mentioning that, given how JavaScript closure works, the variable l (var l = path.getTotalLength();) is accessible to the tween function.

