Skip to content
jshacks.dev
Patterns

Implement the visitor pattern for an AST

Implement the visitor pattern for an AST in JavaScript: one function walks the nodes and a table of visitors does the work. Node.js 24.

1 min read
Summarize in AI

A syntax tree has many node types and you want many operations on it. A visitor keeps each operation in one place, instead of a method on every node class.

JavaScript
const ast = {
  type: 'Add',
  left: { type: 'Num', value: 2 },
  right: { type: 'Mul', left: { type: 'Num', value: 3 }, right: { type: 'Num', value: 4 } },
};

const evaluate = {
  Num: (node) => node.value,
  Add: (node, walk) => walk(node.left) + walk(node.right),
  Mul: (node, walk) => walk(node.left) * walk(node.right),
};

const print = {
  Num: (node) => String(node.value),
  Add: (node, walk) => `(${walk(node.left)} + ${walk(node.right)})`,
  Mul: (node, walk) => `(${walk(node.left)} * ${walk(node.right)})`,
};

const visit = (visitors) => {
  const walk = (node) => visitors[node.type](node, walk);
  return walk;
};

console.log(visit(evaluate)(ast));
console.log(visit(print)(ast));
Text
14
(2 + (3 * 4))

visit builds a walk function that looks up the handler by node.type and passes walk for the children. Adding an operation means adding one object, and the node data does not change.

The trade-off is the opposite one: a new node type needs an entry in every visitor. A missing key throws a TypeError, so test each visitor against every node type.

Taggednode 24
Share

More snippets

Get new posts by email

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

Unsubscribe in one click. No spam, ever.