Skip to content
jshacks.dev
Functions

Implement a Virtual DOM Diff From Scratch in JavaScript

Build a virtual DOM diff from scratch in JavaScript with element nodes, a patch list for props and children, keyed lists and a small apply step. Node.js 24.

8 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Google Chrome, npm, TypeScript and Vite logos.

A virtual DOM diff sounds like framework internals, and in an interview it is a test of recursion and of restraint. The algorithm that frameworks use for real is intricate, but the core idea fits in a page: describe the interface as plain objects, compare the old description with the new one, and produce a short list of changes to apply to the real tree. This post builds that on Node.js 24, with no browser needed, because the diff operates on plain data and the output is a list of patches you can print. It then adds a small apply step against a fake DOM, handles lists with keys and states what the toy version leaves out. For the recursion pattern underneath, see walking a tree structure recursively.

What a virtual node is

A virtual node is a plain object: a tag, a props object and an array of children, where a child is either another node or a string of text. A helper called h builds them so the examples stay short.

JavaScript
function h(tag, props = {}, ...children) {
  return { tag, props, children: children.flat() };
}

const before = h("ul", { class: "list" }, h("li", {}, "one"), h("li", {}, "two"));

console.log(JSON.stringify(before));
Text
{"tag":"ul","props":{"class":"list"},"children":[{"tag":"li","props":{},"children":["one"]},{"tag":"li","props":{},"children":["two"]}]}

This is data, so comparing two descriptions costs ordinary object comparison and no layout work. That is the claim behind the whole idea: reading and comparing JavaScript objects is cheap, and touching the real DOM is the expensive part, so you compare in memory and touch the DOM only where the result says it changed.

The patch format

Define the changes the diff can report. A small set is enough.

PatchMeaning
CREATEadd a node at a path
REMOVEdelete the node at a path
REPLACEswap the node at a path for a different one
TEXTchange the text of a text node
PROPSset or remove props on an element

A path is an array of child indexes from the root, such as [0, 1] for "second child of the first child". Paths keep the patch list plain data, which makes it printable and testable.

The diff

Recurse over both trees at once. At each position there are a few cases: one side is missing, the types differ, both are text, or both are elements with the same tag.

JavaScript
function diff(oldNode, newNode, path = [], patches = []) {
  if (oldNode === undefined) {
    patches.push({ type: "CREATE", path, node: newNode });
  } else if (newNode === undefined) {
    patches.push({ type: "REMOVE", path });
  } else if (typeof oldNode === "string" || typeof newNode === "string") {
    if (oldNode !== newNode) {
      patches.push(
        typeof oldNode === "string" && typeof newNode === "string"
          ? { type: "TEXT", path, text: newNode }
          : { type: "REPLACE", path, node: newNode },
      );
    }
  } else if (oldNode.tag !== newNode.tag) {
    patches.push({ type: "REPLACE", path, node: newNode });
  } else {
    const propChanges = diffProps(oldNode.props, newNode.props);

    if (Object.keys(propChanges).length > 0) {
      patches.push({ type: "PROPS", path, props: propChanges });
    }

    const length = Math.max(oldNode.children.length, newNode.children.length);

    for (let i = 0; i < length; i += 1) {
      diff(oldNode.children[i], newNode.children[i], [...path, i], patches);
    }
  }

  return patches;
}

function diffProps(oldProps, newProps) {
  const changes = {};

  for (const key of Object.keys(newProps)) {
    if (oldProps[key] !== newProps[key]) {
      changes[key] = newProps[key];
    }
  }

  for (const key of Object.keys(oldProps)) {
    if (!(key in newProps)) {
      changes[key] = null;
    }
  }

  return changes;
}

Read the branches in order. A missing old node means the new one must be created, and a missing new node means removal. A text node compared with a text node becomes a TEXT patch only if the strings differ, and a text node compared with an element is a replacement. Two elements with different tags cannot be morphed into each other, so the whole subtree is replaced: that rule is the assumption in the real algorithm too, and it is why changing a div to a section rebuilds everything below it. Only when the tags match do we compare props and descend into children, one index at a time.

A removed prop is reported as null, so the apply step knows to delete it and not set it to the string "null".

JavaScript
const after = h(
  "ul",
  { class: "list", id: "main" },
  h("li", {}, "one"),
  h("li", {}, "TWO"),
  h("li", {}, "three"),
);

for (const patch of diff(before, after)) {
  console.log(JSON.stringify(patch));
}
Text
{"type":"PROPS","path":[],"props":{"id":"main"}}
{"type":"TEXT","path":[1,0],"text":"TWO"}
{"type":"CREATE","path":[2],"node":{"tag":"li","props":{},"children":["three"]}}

Three patches for three real differences. The root gained an id. The text inside the second li changed, and its path [1, 0] reads "second child, then its first child". The third li is new. The first li produced nothing, which is the saving: unchanged parts cost a comparison and no DOM work.

Applying patches

A diff is only useful if something consumes it. To keep the example runnable in Node.js with no browser, apply the patches to a tiny fake DOM built from the same plain objects, and have the real version in mind: document.createElement, setAttribute and replaceChild do the same jobs.

JavaScript
function getNode(root, path) {
  return path.reduce((node, index) => node.children[index], root);
}

function apply(root, patches) {
  for (const patch of patches) {
    const { path } = patch;

    if (path.length === 0) {
      if (patch.type === "PROPS") applyProps(root, patch.props);
      continue;
    }

    const parent = getNode(root, path.slice(0, -1));
    const index = path[path.length - 1];

    switch (patch.type) {
      case "CREATE":
        parent.children[index] = patch.node;
        break;
      case "REMOVE":
        parent.children.splice(index, 1);
        break;
      case "REPLACE":
      case "TEXT":
        parent.children[index] = patch.node ?? patch.text;
        break;
      case "PROPS":
        applyProps(parent.children[index], patch.props);
        break;
    }
  }

  return root;
}

function applyProps(node, props) {
  for (const [key, value] of Object.entries(props)) {
    if (value === null) delete node.props[key];
    else node.props[key] = value;
  }
}

const current = structuredClone(before);
apply(current, diff(before, after));

console.log(JSON.stringify(current) === JSON.stringify(after));
Text
true

The patched copy of the old tree equals the new tree, which is the property that defines a correct diff: applying the patches to the old tree must produce the new one. Checking that equality is also the best test, and it is shown below.

There is a trap in apply, and it is the same one real implementations hit. Applying REMOVE patches changes the indexes of the siblings after the removed one. If two nodes are removed, applying the first shifts the second, and the second patch removes the wrong element. The usual fixes are to apply removals from the highest index to the lowest, or to collect them and delete in one pass.

Lists and keys

The index-by-index comparison fails on lists that change in the middle. Insert an item at the front, and every item after it looks changed.

JavaScript
const listA = h("ul", {}, h("li", {}, "b"), h("li", {}, "c"));
const listB = h("ul", {}, h("li", {}, "a"), h("li", {}, "b"), h("li", {}, "c"));

console.log(diff(listA, listB).map((p) => `${p.type}@${p.path.join(".")}`));
Text
[ '[email protected]', '[email protected]', 'CREATE@2' ]

One insertion produced three patches: the first two rewrote their text to shift everything down, and one node was appended. For text that is cheap. For elements that hold state, such as an input with typed text or a focused field, rewriting in place attaches the old state to the wrong item, which is the bug people see when they forget key in React.

Keys fix it by matching old and new children by identity instead of by position. A minimal keyed pass looks like this.

JavaScript
function diffKeyed(oldChildren, newChildren) {
  const oldByKey = new Map(oldChildren.map((c) => [c.props.key, c]));
  const patches = [];

  newChildren.forEach((child, index) => {
    const match = oldByKey.get(child.props.key);

    if (!match) {
      patches.push({ type: "CREATE", index, key: child.props.key });
    } else {
      oldByKey.delete(child.props.key);
    }
  });

  for (const key of oldByKey.keys()) {
    patches.push({ type: "REMOVE", key });
  }

  return patches;
}

const oldItems = [h("li", { key: "b" }), h("li", { key: "c" })];
const newItems = [h("li", { key: "a" }), h("li", { key: "b" }), h("li", { key: "c" })];

console.log(diffKeyed(oldItems, newItems));
Text
[ { type: 'CREATE', index: 0, key: 'a' } ]

Now a single insertion gives a single patch, and b and c keep their identity. This sketch ignores reordering, which a full algorithm reports as moves. The principle is the point: with a stable key, "this item is still here" is a lookup and no longer a guess from the position.

What the toy leaves out

Real libraries add event handlers as props, batch their work, separate the diff from the commit, reuse component instances and use a linear-time heuristic for ordering. They also apply the rule that two elements of different types produce different subtrees, which the toy also uses. A general tree edit-distance algorithm is far more expensive than the heuristic, which is why frameworks accept the "different tag means replace" simplification and ask you for keys: the two assumptions are what make the algorithm fast enough to run on every update.

How to explain the cost

Interviewers often follow the code with a question about complexity. Walking both trees once is linear in the number of nodes, so the diff for a tree with a thousand nodes does about a thousand comparisons. The expensive alternative is a general tree edit distance, which finds the smallest set of changes between any two trees and grows far faster than the size of the tree. The heuristics are what turn an impractical problem into one cheap enough to run on every state change: nodes of different types are never compared, and keys, not search, decide which children correspond.

State the trade clearly. The toy diff can produce more patches than the theoretical minimum, for example when a subtree moved but is rebuilt in the new place. That is acceptable, because a slightly longer patch list is cheaper than the search needed to avoid it.

Testing it

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("identical trees produce no patches", () => {
  const tree = h("div", { id: "x" }, "hello");
  assert.deepEqual(diff(tree, structuredClone(tree)), []);
});

test("a changed tag replaces the node", () => {
  const patches = diff(h("div"), h("section"));
  assert.equal(patches[0].type, "REPLACE");
});

test("applying the patches turns the old tree into the new one", () => {
  const a = h("p", { class: "a" }, "x", h("b", {}, "y"));
  const b = h("p", { class: "b" }, "z", h("b", {}, "y"), h("i", {}, "w"));
  const result = apply(structuredClone(a), diff(a, b));
  assert.deepEqual(result, b);
});
Text
ℹ tests 3
ℹ pass 3
ℹ fail 0
Also inBrowser
Taggedinterview
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.