{"id":12028,"library":"simple-eval","title":"Simple JavaScript Expression Evaluator","description":"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.","status":"active","version":"2.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/P0lip/simple-eval","tags":["javascript","eval","evaluation","code evaluation","code execution","ast","typescript"],"install":[{"cmd":"npm install simple-eval","lang":"bash","label":"npm"},{"cmd":"yarn add simple-eval","lang":"bash","label":"yarn"},{"cmd":"pnpm add simple-eval","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Default AST parser for expression evaluation. Can be replaced with other ESTree-compliant parsers.","package":"jsep","optional":false}],"imports":[{"note":"The library primarily uses ES Module syntax as shown in its documentation and ships TypeScript types. While CommonJS `require` might work in some transpiled environments, `import` is the recommended and modern approach.","wrong":"const simpleEval = require('simple-eval');","symbol":"simpleEval","correct":"import simpleEval from 'simple-eval';"},{"note":"Type import for `simpleEval` function signature, useful when explicitly typing function parameters or variables in TypeScript projects.","symbol":"SimpleEvalFunction","correct":"import type { SimpleEvalFunction } from 'simple-eval';"},{"note":"Type import for configuring a custom AST parser, allowing users to specify a different parser than the default `jsep`.","symbol":"CustomParserOptions","correct":"import type { CustomParserOptions } from 'simple-eval';"}],"quickstart":{"code":"import simpleEval from 'simple-eval';\n\n// Basic arithmetic evaluation\nconst result1 = simpleEval('2 + 4 * 10 + -4');\nconsole.log(`'2 + 4 * 10 + -4' evaluates to: ${result1}`); // Expected: 38\n\n// Using a context object for external variables or functions\nconst context = {\n  Math,\n  user: {\n    name: 'Alice',\n    age: 30,\n    isAdmin: true\n  },\n  greet: (name) => `Hello, ${name}!`\n};\n\nconst result2 = simpleEval('Math.floor(Math.PI * 10)', context);\nconsole.log(`'Math.floor(Math.PI * 10)' with Math context evaluates to: ${result2}`); // Expected: 31\n\nconst result3 = simpleEval('user.isAdmin ? greet(user.name) : \\'Access Denied\\'', context);\nconsole.log(`Conditional access with custom function and object: ${result3}`); // Expected: 'Hello, Alice!'\n\n// Attempting to use an undeclared variable (will throw if not in context)\ntry {\n  simpleEval('unknownVariable + 5');\n} catch (e) {\n  console.error(`Error evaluating 'unknownVariable + 5': ${e.message}`); // Expected: 'unknownVariable is not defined'\n}\n","lang":"typescript","description":"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."},"warnings":[{"fix":"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.","message":"simple-eval is not a full replacement for `eval` and should not be treated as a general-purpose JavaScript interpreter. It intentionally limits supported language features to enhance safety and predictability.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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`.","message":"Declarations (e.g., `const`, `let`, `var`, `function`) and assignments (e.g., `x = 5`, `obj.prop = value`) are explicitly prohibited within the evaluated expressions. Attempting to use them will result in an error.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"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.","message":"The library does not provide a robust security sandbox. While it restricts many dangerous operations, it is not designed to run arbitrary untrusted code in a secure, isolated environment.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"By default, `simple-eval` uses the `jsep` parser. If you encounter parsing issues with specific syntaxes or wish to leverage advanced parsing features (e.g., JSX, Flow, TypeScript), you may need to provide a different ESTree-compliant parser.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"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 })`.","cause":"Attempting to access a variable or function within the evaluated expression that was not passed in the context object.","error":"ReferenceError: <variable> is not defined"},{"fix":"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.","cause":"The evaluated string contains unsupported syntax like variable declarations (`const`, `let`, `var`), function declarations, or assignments (`=`).","error":"SyntaxError: Unexpected token"},{"fix":"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`.","cause":"An object or property within the expression is `undefined` at the time of evaluation.","error":"TypeError: Cannot read properties of undefined (reading 'prop')"}],"ecosystem":"npm"}