Simple JavaScript Expression Evaluator

2.0.0 · active · verified Sun Apr 19

simple-eval is a focused JavaScript library designed for evaluating simple expressions safely, providing an alternative to the native `eval()` function with a controlled execution environment. The current stable version is 2.0.0. It aims for a moderate release cadence, primarily for maintenance, bug fixes, or minor feature additions. A key differentiator is its limited instruction set, which enhances security by disallowing declarations, assignments, and complex statements, making it safer than direct `eval` for untrusted input, though it does not provide a full sandbox. It uses `jsep` as the default AST parser but supports any ESTree compliant parser like `acorn`, `@babel/parser`, or `esprima`, offering flexibility in parsing logic. This makes it suitable for scenarios requiring lightweight, controlled expression evaluation.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic expression evaluation, passing a context object to allow access to `Math` functions, custom objects, and user-defined functions, and shows how to handle errors from undefined variables.

import simpleEval from 'simple-eval';

// Basic arithmetic evaluation
const result1 = simpleEval('2 + 4 * 10 + -4');
console.log(`'2 + 4 * 10 + -4' evaluates to: ${result1}`); // Expected: 38

// Using a context object for external variables or functions
const context = {
  Math,
  user: {
    name: 'Alice',
    age: 30,
    isAdmin: true
  },
  greet: (name) => `Hello, ${name}!`
};

const result2 = simpleEval('Math.floor(Math.PI * 10)', context);
console.log(`'Math.floor(Math.PI * 10)' with Math context evaluates to: ${result2}`); // Expected: 31

const result3 = simpleEval('user.isAdmin ? greet(user.name) : \'Access Denied\'', context);
console.log(`Conditional access with custom function and object: ${result3}`); // Expected: 'Hello, Alice!'

// Attempting to use an undeclared variable (will throw if not in context)
try {
  simpleEval('unknownVariable + 5');
} catch (e) {
  console.error(`Error evaluating 'unknownVariable + 5': ${e.message}`); // Expected: 'unknownVariable is not defined'
}

view raw JSON →