Skip to content

Expression Parser

Minified: 5.51 KBGzip: 2.02 KBBrotli: 1.79 KBZstd: 2.05 KB

A non-visual Web Component for safely parsing and evaluating user-defined expressions.
It renders nothing so importing it is enough to make it available via customElements.get.

Instead of relying on eval() or new Function(), this component builds an Abstract Syntax Tree (AST) from the input string and walks it in a controlled environment.
This gives you full introspection over what an expression does before and after running it.

Security

Sandboxed Evaluation

Expressions are never executed as JavaScript source. The AST evaluator controls every operation explicitly.

Allowed Globals

Expressions can only reference the following built-ins directly:

(Math, JSON, Date, Object, Array, String, Number, Boolean, Symbol);

Everything else is resolved through the variable getter you supply.

Blocked Property Names

Accessing any of the following properties throws at evaluation time, regardless of the object:

(__proto__, prototype, constructor, __defineGetter__, __defineSetter__);

Supported Literals

TypeExamples
String"hello", 'world'
Number42, 3.14
Booleantrue, false
Nullishnull, undefined
Numeric constantsInfinity, NaN

Supported Operators

CategoryOperators
Arithmetic+ - * / %
Comparison< <= > >=
Equality== != === !==
Logical&& || ??
Unary! + - ~
Ternarya ? b : c

Access Patterns

  • Variables: resolved through the getter: price
  • Dot access: user.name
  • Computed access: items[0], record[key]
  • Calls: Math.round(x), fn(a, b)

Expression Chaining

Comma-separated expressions are all evaluated left to right. The result of the last one is returned, matching JavaScript’s comma operator semantics.

Parser.parse("x * 2, y * 2, x + y");
// evaluates all three, returns the value of x + y

Usage

Parsing

const Parser = customElements.get("wcp-expression-parser") as typeof ExpressionParser;
const ast = Parser.parse("quantity * unitPrice");

Evaluating

Supply a getter function that receives a variable name and its parent node, and returns its value.

const result = Parser.evaluate(ast, (name, parentNode) => context[name]);

Extracting Dependencies

Get every variable name referenced in an expression, useful for building reactive systems.

const ast = Parser.parse("a + b * c");
const deps = Parser.usedVariables(ast); // Set(["a", "b", "c"])

AST Node Reference

NodeRepresents
LiteralA fixed value — string, number, boolean, null
VariableAn identifier looked up via the getter
MemberProperty access, dot or computed
CallA function or method invocation
UnaryA single-operand operation
BinaryA two-operand operation
TernaryA conditional expression
SequenceA comma-separated chain of expressions