Course contentsShow
← Web Development
Lesson 2629 of 2,98247. Data VisualizationFree lesson

Selections and the Enter-Update-Exit Pattern

Learn how D3 selections work and the fundamental pattern for handling data joins.

Selections and the Enter-Update-Exit Pattern

You'll learn how D3 manages the relationship between data and DOM elements through its fundamental selection pattern.

What Are D3 Selections?

In D3, a selection is a group of DOM elements that you want to manipulate. Unlike directly creating SVG elements, D3 binds data to selections and then lets you specify what should happen based on whether elements already exist or not.

Think of it like assigning seats at a dinner party: you have a list of guests (your data) and a set of chairs (DOM elements). Some guests might already be seated, some need new chairs, and some chairs might be empty if guests left.

The Enter-Update-Exit Pattern

This is D3's core mechanism for synchronizing data with elements:

  1. Enter: New data items that don't have corresponding DOM elements yet (guests arriving who need chairs)
  2. Update: Existing data items matched with existing DOM elements (guests already seated)
  3. Exit: Old DOM elements that no longer have matching data (empty chairs after guests leave)
const data = [10, 20, 30];

// Select all circles, bind data
const circles = d3.select('svg')
  .selectAll('circle')
  .data(data);

// ENTER: create new circles for new data
circles.enter()
  .append('circle')
  .attr('r', 5);

// UPDATE: modify existing circles
circles.attr('cx', d => d);

// EXIT: remove circles with no data
circles.exit().remove();

This pattern ensures your visualization always reflects your current dataset, whether it grows, shrinks, or changes.

Key Takeaway: D3's Enter-Update-Exit pattern creates a declarative way to keep DOM elements synchronized with data arrays—new data creates elements (enter), existing data updates elements (update), and removed data deletes elements (exit).