Function constructor can be used as safe alternative to eval

How do you run arbitrary code provided as string in JavaScript when you should not use eval?

Answer: Function constructor

js
const logFn = console.log;
const minusFn = (a, b) => a - b;
const codeRunner = new Function(
// code will have access to `log` and `minus` parameter
'log',
'minus',
`
var x = 100;
var y = 100;
log(x + y);
log(minus(x, y));
` // string to be evaluated as code
);
codeRunner(logFn, minusFn);
// provide the `log` and `minus` parameter

The difference of Function constructor and eval is that eval has access to local variable where you run it, while Function constructor only has access to the parameters provided and global variables only.

What's the use of this? Not much, but it enables the code snippet in this site to be edited and run safely.

Topics

  • javascript