liveBook · Manning

Arrow function

As explained in D3.js in Action, Third Edition

An arrow function is JavaScript function syntax that uses an arrow notation and supports concise expression or block bodies.

An arrow function is compact JavaScript function syntax used here as a D3 accessor: it receives bound data and returns an attribute value for each SVG rectangle. section 3.3.1

Use these formatting rules:

  • Omit parentheses around one parameter, as in d => d.count; wrap multiple parameters, as in (d, i). section 3.3.1
  • Return a single expression directly; use braces and an explicit return statement for a multiline function body. section 3.3.1
  • Use the index parameter to calculate positions, such as placing each bar five pixels below the previous one. section 3.3.1
const barHeight = 20;
svg
  .selectAll("rect")
  .data(data)
  .join("rect")
    .attr("class", d => {
      console.log(d);
      return "bar";
    })
    .attr("width", d => d.count)
    .attr("height", barHeight)
    .attr("x", 0)
    .attr("y", (d, i) => (barHeight + 5) * i)

This D3 chain uses arrow functions to derive rectangle width from data and vertical position from the data index. section 3.3.1

Highlighting one bar

An arrow function can also choose an attribute conditionally: d => d.technology === "D3.js" ? "yellowgreen" : "skyblue". section 3.3.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains parameter formatting, expression versus block bodies, returns, and index-based positioning without covering broader function behavior.
Examples
Demonstrates bar-chart rectangles, data-derived widths, indexed vertical positions, multiline class accessors, and conditional colors.
What it assumes
Assumes familiarity with JavaScript arrays, loops, D3 data binding, and SVG rectangles while reinforcing callback syntax.
What you can do after
Apply arrow functions in D3 chains to calculate SVG dimensions, positions, classes, and colors from bound data.
How it connects
Connects arrow functions with D3, data binding, accessor functions, SVG attributes, arrays, and zero-based indexes.

Also explained in

Compare how 7 books explain arrow function →

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.