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.
npm install simple-evalVerified import paths — ran on the pinned version, not inferred.
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.
Always review the 'Caveats' section of the documentation to understand the supported language constructs. For complex script execution or full JavaScript runtime, consider dedicated sandboxing solutions or Node.js `vm` module.
Ensure that your expressions only contain valid evaluable constructs without altering scope or state. Pass all necessary variables and functions through the context object provided as the second argument to `simpleEval`.
For high-security use cases involving untrusted code, combine `simple-eval` with a proper sandbox solution (e.g., Node.js `vm` module with careful context configuration, or web workers for browser environments) rather than relying solely on its internal restrictions.
To use a different parser, provide a `parser` option in the context object. For example: `simpleEval('...', { parser: customAcornParserInstance })`. Ensure the custom parser outputs an ESTree-compliant AST.Ensure all variables, objects, and functions required by the expression are explicitly provided in the second argument to `simpleEval`. Example: `simpleEval('myVar + 1', { myVar: 10 })`.Remove all declarations and assignments from the expression. `simple-eval` is designed for expressions only. If you need to mutate state, do so outside the evaluation and pass the updated values in the context.
Check the context object and the expression logic to ensure all object paths are valid and defined. For optional chaining-like behavior, use ternary operators or logical AND (`&&`) within the expression: `user && user.profile && user.profile.name`.