JavaScript Expression Evaluator


This library is a modified version of Raphael Graf’s ActionScript Expression Parser (formerly at When I wrote the JavaScript Function Plotter, I wanted a better alternative to using JavaScript’s eval function. There’s no security risk currently, because you can only run code in your own browser, but it’s not as convenient for math (Math.pow(2, x) instead of 2^x, etc.).


Get the code from github.

Documentation (incomplete, of course)


Parser is the main class in the library. It has “static” methods for parsing and evaluating expressions.

Constructor. In most cases, you don’t need this. Eventually, I’ll get around to documenting why you would want to, but for now, you can figure it out by reading the source ;-).
<dt>parse({expression: string})</dt>
<dd>Convert a mathematical expression into an Expression object.</dd>

<dt>evaluate({expression: string} [, {variables: object}])</dt>
<dd>Parse and immediately evaluate an expression using the values/functions from the {variables} object.</dd>
<dd><code>Parser.evaluate(expr, vars)</code> is equivalent to calling <code>Parser.parse(expr).evaluate(vars)</code>. In fact, that’s exactly what it does.</dd>


Parser.parse returns an Expression object. Expression's are similar to JavaScript functions, i.e. they can be “called” with variables bound to passed-in values. In fact, they can even be converted into JavaScript functions.

evaluate([{variables: object}])
Evaluate an expression, with variables bound to the values in {variables}. Each unbound variable in the expression is bound to the corresponding member of the {variables} object. If there are unbound variables, evaluate will throw an exception.
js> expr = Parser.parse("2 ^ x");
js> expr.evaluate({ x: 3 });
<dt>substitute({variable: string}, {expr: Expression, string, or number})</dt>
<dd>Create a new expression with the specified variable replaced with another expression (essentially, function composition).</dd>
	<pre><code>js> expr = Parser.parse("2 * x + 1");

js> expr.substitute("x", "4 * x");
js> expr2.evaluate({ x: 3});

<dt>simplify({variables: object>)</dt>
<dd>Simplify constant sub-expressions and replace variable references with literal values. This is basically a partial evaluation, that does as much of the calcuation as it can with the provided variables. Function calls are not evaluated (except the built-in operator functions), since they may not be deterministic.</dd>
<dd>Simplify is pretty simple (see what I did there?). It doesn’t know that addition and multiplication are associative, so “((2*(4*x))+1)” from the previous example cannot be simplified unless you provide a value for x. “2*4*x + 1″ can however, because it’s parsed as “(((2*4)*x)+1)”, so the “(2*4)” sub-expression will be replaced with “8″, resulting in “((8*x)+1)”.</dd>
	<pre><code>js> expr = Parser.parse("x * (y * atan(1))").simplify({ y: 4 });

js> expr.evaluate({ x: 2 });

<dd>Get an array of the unbound variables in the expression.</dd>
	<pre><code>js> expr = Parser.parse("x * (y * atan(1))");

js> expr.variables();
js> expr.simplify({ y: 4 }).variables();

<dd>Convert the expression to a string. toString() surrounds every sub-expression with parentheses (except literal values, variables, and function calls), so it’s useful for debugging precidence errors.</dd>

<dt>toJSFunction({parameters: Array} [, {variables: object}])</dt>
<dd>Convert an Expression object into a callable JavaScript function. You need to provide an array of parameter names that should normally be <code>expr.variables()</code>. Any unbound-variables will get their values from the global scope.</dd>
<dd><code>toJSFunction</code> works by simplifying the Expression (with {variables}, if provided), converting it to a string, and passing the string to the <code>Function</code> constructor (with some of its own code to bring built-in functions and constants into scope and return the result of the expression).</dd>

Expression Syntax

The parser accepts a pretty basic grammar. Operators have the normal precidence — f(x,y,z) (function calls), ^ (exponentiation), *, /, and % (multiplication, division, and remainder), and finally +, -, and || (addition, subtraction, and string concatenation) — and bind from left to right (yes, even exponentiation… it’s simpler that way).

There’s also a “,” (comma) operator that concatenates values into an array. It’s mostly useful for passing arguments to functions, since it doesn’t always behave like you would think with regards to multi-dimensional arrays. If the left value is an array, it pushes the right value onto the end of the array, otherwise, it creates a new array “[left, right]“. This makes it impossible to create an array with another array as it’s first element.

Function operators

The parser has several built-in “functions” that are actually operators. The only difference from an outside point of view, is that they cannot be called with multiple arguments and they are evaluated by the simplify method if their arguments are constant.

Function Description
sin(x) Sine of x (x is in radians)
cos(x) Cosine of x (x is in radians)
tan(x) Tangent of x (x is… well, you know)
asin(x) Arc sine of x (in radians)
acos(x) Arc cosine of x (in radians)
atan(x) Arc tangent of x (in radians)
sqrt(x) Square root of x. Result is NaN (Not a Number) if x is negative.
log(x) Natural logarithm of x (not base-10). It’s log instead of ln because that’s what JavaScript calls it.
abs(x) Absolute value (magnatude) of x
ceil(x) Ceiling of x — the smallest integer that’s >= x.
floor(x) Floor of x — the largest integer that’s <= x
round(x) X, rounded to the nearest integer, using “gradeschool rounding”.
exp(x) ex (exponential/antilogarithm function with base e)

Pre-defined functions

Besides the “operator” functions, there are several pre-defined functions. You can provide your own, by binding variables to normal JavaScript functions. These are not evaluated by simplify.

Function Description
random(n) Get a random number in the range [0, n). If n is zero, or not provided, it defaults to 1.
fac(n) n! (factorial of n: “n * (n-1) * (n-2) * … * 2 * 1″)
min(a,b,…) Get the smallest (“minimum”) number in the list
max(a,b,…) Get the largest (“maximum”) number in the list
pyt(a, b) Pythagorean function, i.e. the c in “c2 = a2 + b2
pow(x, y) xy. This is exactly the same as “x^y”. It’s just provided since it’s in the Math object from JavaScript
atan2(y, x) arc tangent of x/y. i.e. the angle between (0, 0) and (x, y) in radians.