D3.js tutorial - Part 4 - Method chaining


Method chaining is a syntax for calling several methods in one instruction on the same instance. It can be done if each method returns the current object (this). Here is a typical example of method chaining:


Most of the D3.js functions allows method chaining which is commonly used while creating charts with D3.js.

D3.js example

Let's keep the last example of the previous part. In this example, a <h1> element was created, then a text was added and finaly the color was set to red. Here is the previous code:

d3.select('h1').text('This tag and text has been added with D3.js');
d3.select('h1').style('color', 'red');

This code can be rewritten using method chaining, because each function returns the element selected:

Order of execution

A question still remains, in the following example, which is called first?


method1() is necessary called before method2(). Otherwise, since method1() is not already called, method2() has no returned object to process. The following example confirms the previous statement where the last method is called in last.

// Method chaining order

In conclusion, methods are called from left to right.

See also

Last update : 10/12/2021