Skip to content
jshacks.dev
Patterns

Interpreter Pattern in JavaScript, With Real Examples

The Interpreter pattern models a small language as a tree of objects that each know how to evaluate themselves. Build one in JavaScript for rule expressions.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Vite, Node.js and npm logos.

The Interpreter pattern represents the sentences of a small language as a tree of objects, where each node knows how to evaluate itself against some context. It fits problems like rule engines, filters and query expressions, where users or configuration describe logic that your program has to run. This post builds one in JavaScript on Node.js 24: a tiny rule language with a tokenizer, a parser and an evaluator, then shows when plain functions are enough.

The problem: logic that arrives as text

Suppose an admin screen lets someone type a rule such as age >= 18 and country == "VN", and your code must apply it to many users. You could use eval, but that executes arbitrary code and is a security hole. You could write one hardcoded filter per rule, but then every new rule needs a deploy. An interpreter turns the text into a structure your code controls.

Step 1: the node classes

Each kind of expression is a class with one method, evaluate(context).

nodes.mjsJavaScript
class Literal {
  constructor(value) {
    this.value = value;
  }
  evaluate() {
    return this.value;
  }
}

class Variable {
  constructor(name) {
    this.name = name;
  }
  evaluate(context) {
    return context[this.name];
  }
}

class Compare {
  constructor(op, left, right) {
    this.op = op;
    this.left = left;
    this.right = right;
  }
  evaluate(context) {
    const a = this.left.evaluate(context);
    const b = this.right.evaluate(context);
    switch (this.op) {
      case "==":
        return a === b;
      case ">=":
        return a >= b;
      case "<":
        return a < b;
      default:
        throw new Error(`unknown operator ${this.op}`);
    }
  }
}

class And {
  constructor(left, right) {
    this.left = left;
    this.right = right;
  }
  evaluate(context) {
    return this.left.evaluate(context) && this.right.evaluate(context);
  }
}

class Or {
  constructor(left, right) {
    this.left = left;
    this.right = right;
  }
  evaluate(context) {
    return this.left.evaluate(context) || this.right.evaluate(context);
  }
}

You can already build a rule by hand and run it. This is the core of the pattern: a tree whose nodes evaluate recursively.

manual.mjsJavaScript
const rule = new And(
  new Compare(">=", new Variable("age"), new Literal(18)),
  new Compare("==", new Variable("country"), new Literal("VN")),
);

console.log(rule.evaluate({ age: 20, country: "VN" }));
console.log(rule.evaluate({ age: 16, country: "VN" }));
console.log(rule.evaluate({ age: 30, country: "US" }));
Text
true
false
false

The nodes are the grammar. A new operator, such as not or in, is a new class or a new case.

Step 2: the tokenizer

A tokenizer splits the text into pieces the parser can consume. Words, numbers, quoted strings and operators are enough here.

tokenize.mjsJavaScript
function tokenize(input) {
  const source = input.trim();
  const pattern = /\s*(>=|==|<|\(|\)|"[^"]*"|\d+|[A-Za-z_]\w*)/gy;
  const tokens = [];
  let match;
  while (pattern.lastIndex < source.length && (match = pattern.exec(source))) {
    tokens.push(match[1]);
  }
  if (pattern.lastIndex !== 0 && pattern.lastIndex < source.length) {
    throw new Error("unexpected input");
  }
  if (!match && source.length > 0) throw new Error("unexpected input");
  return tokens;
}

console.log(tokenize('age >= 18 and country == "VN"'));
Text
[ 'age', '>=', '18', 'and', 'country', '==', '"VN"' ]

The y flag makes the regular expression sticky, so each match must start exactly where the last one ended. Without it, exec would skip over junk characters and hide errors.

Step 3: the parser

The parser turns tokens into the node tree. A recursive descent parser has one function per grammar rule, and precedence falls out of which function calls which. Here or binds loosest, then and, then comparisons.

parse.mjsJavaScript
function parse(source) {
  const tokens = tokenize(source);
  let pos = 0;

  const peek = () => tokens[pos];
  const next = () => tokens[pos++];

  function parseOr() {
    let left = parseAnd();
    while (peek() === "or") {
      next();
      left = new Or(left, parseAnd());
    }
    return left;
  }

  function parseAnd() {
    let left = parseCompare();
    while (peek() === "and") {
      next();
      left = new And(left, parseCompare());
    }
    return left;
  }

  function parseCompare() {
    const left = parsePrimary();
    if ([">=", "==", "<"].includes(peek())) {
      const op = next();
      return new Compare(op, left, parsePrimary());
    }
    return left;
  }

  function parsePrimary() {
    const token = next();
    if (token === undefined) throw new Error("unexpected end of rule");
    if (token === "(") {
      const inner = parseOr();
      if (next() !== ")") throw new Error("expected )");
      return inner;
    }
    if (/^\d+$/.test(token)) return new Literal(Number(token));
    if (token.startsWith('"')) return new Literal(token.slice(1, -1));
    return new Variable(token);
  }

  const tree = parseOr();
  if (pos < tokens.length) throw new Error(`unexpected token ${peek()}`);
  return tree;
}

const rule = parse('age >= 18 and (country == "VN" or country == "US")');
console.log(rule.evaluate({ age: 20, country: "US" }));
console.log(rule.evaluate({ age: 20, country: "FR" }));
console.log(rule.evaluate({ age: 15, country: "VN" }));
Text
true
false
false

The parenthesized group works because parsePrimary calls back into parseOr. Because parseAnd is called from parseOr, a or b and c parses as a or (b and c), which matches what most people expect.

Step 4: errors a user can read

Rules typed by people will have mistakes, and the interpreter is the place to report them.

errors.mjsJavaScript
for (const source of ['age >=', 'age >= 18 and', '(age >= 18', 'age >= 18 )']) {
  try {
    parse(source);
  } catch (err) {
    console.log(`${source} -> ${err.message}`);
  }
}
Text
age >= -> unexpected end of rule
age >= 18 and -> unexpected end of rule
(age >= 18 -> expected )
age >= 18 ) -> unexpected token )

Parsing before evaluating means a bad rule is rejected when it is saved, not when it first meets a real user.

Evaluating safely

An interpreter is safe because it can only do what its nodes do. Variable reads a key from the context, and nothing in the language can call functions or touch globals. One detail still deserves care: context[this.name] follows the prototype chain, so a rule that mentions constructor or toString would read inherited members.

safe-context.mjsJavaScript
const context = Object.create(null);
context.age = 20;

class SafeVariable {
  constructor(name) {
    this.name = name;
  }
  evaluate(ctx) {
    return Object.hasOwn(ctx, this.name) ? ctx[this.name] : undefined;
  }
}

console.log(new SafeVariable("age").evaluate(context));
console.log(new SafeVariable("constructor").evaluate({ age: 1 }));
Text
20
undefined

Object.hasOwn limits lookups to the context's own keys. For user-supplied rules, this is the small hardening that keeps the language closed.

Testing the interpreter

Table-driven tests suit a language well: each row is a source string, a context and the expected result.

rules.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";

const cases = [
  ['age >= 18', { age: 18 }, true],
  ['age < 18', { age: 18 }, false],
  ['a == 1 or b == 2 and c == 3', { a: 1, b: 0, c: 0 }, true],
  ['(a == 1 or b == 2) and c == 3', { a: 1, b: 0, c: 0 }, false],
];

for (const [source, context, expected] of cases) {
  test(source, () => {
    assert.equal(parse(source).evaluate(context), expected);
  });
}
Text
✔ age >= 18 (0.8ms)
✔ age < 18 (0.1ms)
✔ a == 1 or b == 2 and c == 3 (0.1ms)
✔ (a == 1 or b == 2) and c == 3 (0.1ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0

The last two rows pin down precedence, which is the part most likely to break when someone edits the parser.

The alternative: build rules as functions

If the rules come from your own code and not from text, you do not need a parser. Composing functions gives the same power with less machinery.

combinators.mjsJavaScript
const gte = (key, n) => (ctx) => ctx[key] >= n;
const eq = (key, v) => (ctx) => ctx[key] === v;
const and = (...fns) => (ctx) => fns.every((f) => f(ctx));
const or = (...fns) => (ctx) => fns.some((f) => f(ctx));

const rule = and(gte("age", 18), or(eq("country", "VN"), eq("country", "US")));
console.log(rule({ age: 20, country: "US" }), rule({ age: 20, country: "FR" }));
Text
true false

The Interpreter pattern earns its cost when the rule exists as data: stored in a database, typed by an admin, or sent from another service.

When not to use it

A grammar with many rules turns into a lot of classes, and at that point a parser generator or an existing library is a better foundation than handwritten code. If you only need to filter a list with a few fixed conditions, an array of predicate functions is simpler. And if the language needs loops, functions and variables, you are writing a programming language, and the pattern no longer bounds the work.

Growing the language without losing control

A rule language tends to grow, and each addition tests whether the design holds. A few extensions show where the work lands.

Adding not means one new node class and one new case in the parser, placed at the level where a prefix operator binds: tighter than comparison, looser than a parenthesized group. Adding in, as in country in ("VN", "US"), needs a list literal in the grammar, which means the tokenizer must recognize a comma and the parser must read a sequence. Adding functions, such as lower(name) == "ada", is the point where you should stop and decide how much language you are willing to own, because each function is a new surface that users will depend on and that you must keep stable.

Keep three habits as the grammar grows. First, write the grammar down, in a comment above the parser, as a few lines such as or := and ("or" and)*. A parser with no written grammar is hard to extend, because the precedence rules exist only in the shape of the code. Second, version stored rules. If rules live in a database and you change the meaning of an operator, old rules change meaning with it, so store a language version next to each rule or never change an existing operator. Third, bound the cost. A rule that nests a thousand parentheses can exhaust the call stack in a recursive parser, and a hostile or careless rule should be rejected with a limit on length and depth before it reaches the parser.

What to return to the user

When a rule fails to parse, the message is the product. Include the token that caused the error and its position, so the person typing can find it. The tokenizer above does not record positions, and adding them means tokens become small objects with a text and an index instead of plain strings. That change is worth making the first time a real user asks why their rule was rejected.

Interpreter and compilation

Walking a tree for every user is fine for thousands of evaluations. If one rule is evaluated millions of times, you can compile it once into a closure, by turning each node into a function and composing them, and then call that function. The combinator version above is exactly that target. Parse the text once into a tree, convert the tree to functions once, and keep the function. This gets most of the speed benefit without generating source code, and it avoids eval and new Function, which reopen the security problem the interpreter was meant to close.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 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.