Full answer
Evaluating 2 + 3 * 4 correctly needs precedence and parentheses, and eval on user input is a security hole. A small parser is the safe answer, and it shows how real parsers work.
Step 1, tokenize: scan the text and produce tokens such as { type: 'num', value: 3 }, operators, parentheses, commas, and identifiers. A regular expression with the sticky flag (y) that matches at the current position is a short way to do it. Throw an error with the position on an unknown character.
Step 2, parse with recursive descent. The grammar, from lowest to highest precedence:
expression = term (('+' | '-') term)*term = unary (('*' | '/') unary)*unary = '-' unary | powerpower = primary ('^' unary)?, which is right associative, so2^3^2is2^(3^2)primary = number | identifier | identifier '(' arguments ')' | '(' expression ')'
Each rule is a function. A loop handles left associative operators, so 10 - 4 - 3 becomes (10 - 4) - 3. A higher precedence rule is called from a lower one, which is how the precedence is enforced without a table. The functions return AST nodes such as { type: 'binary', op, left, right }.
Step 3, evaluate: a recursive function with a switch on the node type, using a variables object and an allow list of functions (max, min, sqrt). Unknown names throw an error. Never look up names with eval or new Function.
Good error messages need the token position. Also test the edge cases: unary minus (-(2+3), 2 * -3), nested parentheses, missing closing parenthesis, and division by zero (which gives Infinity in JavaScript, so decide whether to throw).
function tokenize(text) {
const pattern = /\s*(?:(\d+(?:\.\d+)?)|([A-Za-z_]\w*)|(.))/y;
const tokens = [];
while (pattern.lastIndex < text.length) {
const match = pattern.exec(text);
if (!match) break;
const [whole, num, name, other] = match;
const lexeme = num ?? name ?? other;
const pos = match.index + whole.length - lexeme.length;
if (num !== undefined) tokens.push({ type: 'num', value: Number(num), pos });
else if (name !== undefined) tokens.push({ type: 'name', value: name, pos });
else if ('+-*/^(),'.includes(other)) tokens.push({ type: other, pos });
else throw new SyntaxError(`Unexpected character "${other}" at ${pos}`);
}
return tokens;
}
function parse(text) {
const tokens = tokenize(text);
let i = 0;
const peek = () => tokens[i]?.type;
const eat = (type) => {
if (peek() !== type) throw new SyntaxError(`Expected ${type} but found ${peek() ?? 'end of input'}`);
return tokens[i++];
};
function expression() {
let node = term();
while (peek() === '+' || peek() === '-') node = { type: 'binary', op: tokens[i++].type, left: node, right: term() };
return node;
}
function term() {
let node = unary();
while (peek() === '*' || peek() === '/') node = { type: 'binary', op: tokens[i++].type, left: node, right: unary() };
return node;
}
function unary() {
if (peek() === '-') { i++; return { type: 'neg', arg: unary() }; }
return power();
}
function power() {
const base = primary();
if (peek() === '^') { i++; return { type: 'binary', op: '^', left: base, right: unary() }; }
return base;
}
function primary() {
const token = tokens[i];
if (!token) throw new SyntaxError('Unexpected end of input');
if (token.type === 'num') { i++; return { type: 'num', value: token.value }; }
if (token.type === 'name') {
i++;
if (peek() !== '(') return { type: 'var', name: token.value };
i++;
const args = [];
if (peek() !== ')') {
do { args.push(expression()); } while (peek() === ',' && i++);
}
eat(')');
return { type: 'call', name: token.value, args };
}
if (token.type === '(') { i++; const inner = expression(); eat(')'); return inner; }
throw new SyntaxError(`Unexpected ${token.type} at ${token.pos}`);
}
const ast = expression();
if (i < tokens.length) throw new SyntaxError(`Unexpected ${tokens[i].type} at ${tokens[i].pos}`);
return ast;
}
const FUNCTIONS = { max: Math.max, min: Math.min, sqrt: Math.sqrt };
function evaluate(node, vars = {}) {
switch (node.type) {
case 'num': return node.value;
case 'var':
if (!Object.hasOwn(vars, node.name)) throw new ReferenceError('Unknown variable ' + node.name);
return vars[node.name];
case 'neg': return -evaluate(node.arg, vars);
case 'call':
if (!Object.hasOwn(FUNCTIONS, node.name)) throw new ReferenceError('Unknown function ' + node.name);
return FUNCTIONS[node.name](...node.args.map((arg) => evaluate(arg, vars)));
case 'binary': {
const a = evaluate(node.left, vars);
const b = evaluate(node.right, vars);
return { '+': a + b, '-': a - b, '*': a * b, '/': a / b, '^': a ** b }[node.op];
}
}
}
const calc = (text, vars) => evaluate(parse(text), vars);
console.log(calc('2 + 3 * 4'), calc('(2 + 3) * 4'), calc('10 - 4 - 3'), calc('2 ^ 3 ^ 2'));
console.log(calc('-(2 + 3)'), calc('2 * -3'), calc('-2 ^ 2'), calc('2 ^ -1'));
console.log(calc('max(1, x * 2, 3) + sqrt(16)', { x: 5 }));
console.log(JSON.stringify(parse('1 + 2 * 3')));
for (const bad of ['2 +', '(1 + 2', '2 $ 3', 'foo + 1', 'eval(1)', '1 2']) {
try {
calc(bad);
} catch (error) {
console.log(JSON.stringify(bad), '->', error.name + ': ' + error.message);
}
}Run with Node.js v24.22.1 as js-110.js; two runs gave identical output. Output: 14 20 3 512 -5 -6 -4 0.5 14 {"type":"binary","op":"+","left":{"type":"num","value":1},"right":{"type":"binary","op":"*","left":{"type":"num","value":2},"right":{"type":"num","value":3}}} "2 +" -> SyntaxError: Unexpected end of input "(1 + 2" -> SyntaxError: Expected ) but found end of input "2 $ 3" -> SyntaxError: Unexpected character "$" at 2 "foo + 1" -> ReferenceError: Unknown variable foo "eval(1)" -> ReferenceError: Unknown function eval "1 2" -> SyntaxError: Unexpected num at 2
Key points
- Three steps: tokenize, parse to an AST, evaluate; eval is unsafe for untrusted input.
- One parsing function per precedence level; loops give left associativity.
- Exponent is right associative; unary minus sits between multiplication and power.
- Evaluate with an allow list of functions and a variables object.
- Report errors with positions and test unary minus, nesting, and missing parentheses.
Common mistakes
- Using eval or new Function on user input.
- Making all operators one precedence level and ignoring the grammar.
- Parsing left associative operators with recursion and getting the wrong grouping.
- Looking up function names on a plain object without hasOwn, which exposes inherited properties.
Follow-ups
- How would the Pratt parsing technique replace the precedence functions?
- How would you add comparison operators and a ternary operator?
- How would you report line and column numbers for errors?
Tips
- Write the grammar first, lowest precedence at the top.
- Say that loops give left associativity and right recursion gives exponent associativity.
- Always mention why eval is not acceptable.