eval-expression

Evaluate an expression and get what you expect.


Keywords
eval, code, execute, evaluate, return, value
License
MIT
Install
npm install eval-expression@1.0.0

Documentation

Build status  Coveralls  David DM

eval-expression

Evaluate an expression and get what you expect.

Be warned: Take all precausions which apply to using eval. eval-expression is no safer, no more performant and no easier to debug.

But it is more predictable. And, just as eval, it sometimes is useful for rapid prototyping.

Installation

> npm install eval-expression

Usage

var evalExpression = require("eval-expression");


// `eval` fails with function expressions – `evalExpression` handles them.
var sayHello = evalExpression('function () {console.log("Hello!");}');
sayHello();  // Logs: Hello!

// `eval` fails with object literals – `evalExpression` does what you expect.
var fruit = evalExpression('{sort: "pear"}');
fruit;  // Outputs: {sort: "pear"}


// You can access variables in the current scope.
console.log(evalExpression("fruit"));  // Outputs: {sort: "pear"}


// `evalExpression` is only intended to evaluate expressions, not other
// statements.
var tasty;

// So don't do this:
evalExpression('if (fruit.sort == "pear") {tasty = true}');  // Throws

// Do this instead:
tasty = evalExpression('fruit.sort == "pear" ? true : false');  // Outputs: true

// …or even:
tasty = evalExpression('fruit.sort == "pear"');  // Outputs: true

API

evalExpression(expression)

expression

Type: String
Required

A single expression. It will be evaluated in an enclosed scope.

Why use it

eval doesn't always work as you'd expect. See these cases:

License

MIT Β© Tomek Wiszniewski.