## Eval
this is a powerful syntax
```js
var a = 5;
var b = 10;
eval("a+b");
//Gives me output 15
```

## [safe-eval](https://www.npmjs.com/package/safe-eval)
The problem with `eval` is that it is not safe. It is dangerous to run untrusted code because they can access global variables.
`safe-eval` lets you execute JavaScript code without having to use the much discouraged and feared upon `eval()`. `safe-eval` has access to all the standard APIs of the [V8 JavaScript Engine](https://code.google.com/p/v8/). By default, it does not have access to the Node.js API, but can be given access using a conext object. It is implemented using [node's vm module](https://nodejs.org/api/vm.html).
Currently, it works only with Node.js, and the JavaScript code must be an expression (something which evaluates to a value).
### Example
```js
// string concatenation
var code = '"app" + "le"'
var evaluated = safeEval(code) // "apple"
```
```js
// math
var code = 'Math.floor(22/7)'
var evaluated = safeEval(code) // 3.142857142857143
```
```js
// JSON
var code = '{name: "Borat", hobbies: ["disco dance", "sunbathing"]}'
var evaluated = safeEval(code) // {name: "Borat", hobbies: ["disco dance", "sunbathing"]}
```
```js
// function expression
var code = '(function square(b) { return b * b; })(5)'
var evaluated = safeEval(code) // 25
```
```js
// no access to Node.js objects
var code = 'process'
safeEval(code) // THROWS!
```
```js
// your own context API - access to Node's process object and a custom function
var code = '{pid: process.pid, apple: a()}'
var context = {
process: process,
a: function () { return 'APPLE' }
}
var evaluated = safeEval(code, context) // { pid: 16987, apple: 'APPLE' }
```
```js
// pass an options object to the vm
var code = 'process'
safeEval(code, {}, { filename: 'myfile.js'}) // myfile.js can be seen in the stacktrace
```
## Isolated-vm
`safe-eval` is using `vm` under the hood and will get deprecated in nodejs soon. we should use [isolated-vm](https://github.com/laverdet/isolated-vm)
```ts
import ivm from 'isolated-vm';
const code = `(function() { return 'Hello, Isolate!'; })()`;
const isolate = new ivm.Isolate({ memoryLimit: 8 /* MB */ });
const script = isolate.compileScriptSync(code);
const context = isolate.createContextSync();
// Prints "Hello, Isolate!"
console.log(script.runSync(context));
```
> [!info] see more
> [Introduction to isolated-vm in TypeScript (temporal.io)](https://temporal.io/blog/intro-to-isolated-vm)