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 = ; // `eval` fails with function expressions – `evalExpression` handles them.var sayHello = ;; // Logs: Hello! // `eval` fails with object literals – `evalExpression` does what you expect.var fruit = ;fruit; // Outputs: {sort: "pear"} // You can access variables in the current scope.console; // Outputs: {sort: "pear"} // `evalExpression` is only intended to evaluate expressions, not other// statements.var tasty; // So don't do this:; // Throws // Do this instead:tasty = ; // Outputs: true // …or even:tasty = ; // 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: