Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
JS

JavaScript

The language of the web, on the client, the server and the edge.

Paradigm
Multi-paradigm, prototype-based, functional
Typing
Dynamic, weak (TypeScript adds static types)
Memory
Garbage collected
Runs
V8 / SpiderMonkey / JSC engines (JIT)
Concurrency
Single-threaded event loop, workers
Behavioral pattern

Interpreter

Part of the original GoF book; refactoring.guru omits it from its catalog.

Intent

Defines a grammar for a simple language and an interpreter that evaluates sentences in it.

Problem

Users need to write small rules or expressions (filters, formulas) that the app evaluates.

Solution

Represent each grammar rule as a class; build an abstract syntax tree and evaluate it recursively.

Real-world analogy

Think of it like this

A musician reading sheet music: the notation is a small language that gets interpreted into sound.

Structure

association / extends implements / depends on
Context - variables 4 «interface» AbstractExpression + interpret(context) 1 TerminalExpression + interpret(context) 2 NonterminalExpression - children: Expression[]+ interpret(context) 3

Hover or tap a numbered role to highlight it in the diagram.

  1. 1AbstractExpression — Abstract Expression declares interpret().
  2. 2TerminalExpression — Terminal Expressions handle literals and variables.
  3. 3NonterminalExpression — Nonterminal Expressions represent grammar rules built from other expressions.
  4. 4Context — Context holds information shared during interpretation, such as variable values.

Code example

A JavaScript code sample for Interpreter is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Interpreter when the grammar is simple and efficiency is not critical.

Pros and cons

Pros

  • Easy to change and extend the grammar

Cons

  • Complex grammars become hard to maintain; prefer a parser generator

Relations with other patterns

Check yourself

Check yourself

Users type rules like price > 100 AND stock < 5 that the app evaluates.

Saved in this browser only. Part of Behavioral patterns (0/11).