liveBook · Manning

Method chaining

As explained in D3.js in Action, Third Edition

Method chaining is a programming technique in which successive method calls operate on and return an updated object through a linked call sequence.

Method chaining calls several methods on the same object in sequence. Each call passes an updated object to the next, keeping code concise and readable. section 1.2.5 section 1.4

The assembly-line analogy

A car assembly line adds a hood, wheels, tires, and lights in order: let car = new Car().putOnHood().putOnWheels().putOnTires().putOnLights(); Each method receives the updated car, and call order matters. section 1.2.5

In D3, chaining can select every div, append paragraphs, set a class and text, append spans, and apply bold styling without storing every intermediate selection. section 1.2.5

d3.selectAll("div")
  .append("p")
    .attr("class", "my-class")
    .text("Wow")
  .append("span")
    .text("Even More Wow")
    .style("font-weight", "900");

Read the indentation as a visual sequence: each method continues operating on the current selection, while nested calls make the resulting DOM structure easier to follow. section 1.2.5

How D3.js in Action, Third Edition covers it

How deep it goes
Explains ordered object updates with a car analogy and demonstrates complete D3 selection code without covering broader API internals.
Examples
Demonstrates a car assembly line and a D3 sequence that creates, labels, nests, and styles paragraph and span elements.
What it assumes
Assumes basic JavaScript experience and positions method chaining as preparation for D3 work rather than teaching JavaScript broadly.
What you can do after
Apply it via D3 to create and style nested DOM elements through readable call sequences.
How it connects
Connects method chaining with JavaScript objects, D3 selections, DOM manipulation, and web technologies including HTML, CSS, and SVG.

Also explained in

Compare how 3 books explain method chaining →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.