liveBook · Manning

areNodesEqual

As explained in Build a Frontend Web Framework (From Scratch)

areNodesEqual is a book-specific function that determines whether two virtual DOM nodes satisfy the framework's equality rules.

areNodesEqual decides whether two virtual DOM nodes can be treated as the same during reconciliation. If their types differ, replacement is required; element nodes must also have matching tags. section 8.2.2

The function applies a small set of equality checks:

  • Return false when the nodes have different type properties. section 8.2.2
  • For element nodes, compare their tag names; a changed tag requires destroying the old node and mounting a new one. section 8.2.2
  • For component nodes, compare their tag properties, which identify the component prototype. section 12.1.1
  • Return true for remaining same-type nodes under the simplified implementation. section 8.2.2

Console checks

Test two text nodes with identical or different text, an element and a text node, paragraph and div elements, and two paragraph elements with different content. The implementation separates different types and tags, while same-type non-element nodes reach the final true result. section 8.2.2

Listing 8.6 Comparing two nodes for equality (nodes-equal.js)
import { DOM_TYPES } from './h'

export function areNodesEqual(nodeOne, nodeTwo) {
  if (nodeOne.type !== nodeTwo.type) {              #1
    return false
  }

  if (nodeOne.type === DOM_TYPES.ELEMENT) {
    const { tag: tagOne } = nodeOne
    const { tag: tagTwo } = nodeTwo

    return tagOne === tagTwo          #2
  }

  return true
}

The implementation listing shows the incremental decision structure: compare types, handle element tags, handle component prototypes, then apply the fallback. section 8.2.2

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Defines type, element-tag, and component-prototype checks, while deferring keyed-list support to a later extension.
Examples
Uses text nodes, paragraph and div elements, component prototypes, and keyed Counter components as comparison cases.
What it assumes
Assumes JavaScript objects and DOM_TYPES, while introducing virtual-node types, tags, and component prototypes through implementation.
What you can do after
Build it from scratch: implement and test virtual-node equality checks in JavaScript.
How it connects
Connects virtual DOM nodes, reconciliation, component nodes, keyed lists, and the DOM API.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.