eval more like evil
Evaluating a string of code as code is a very useful thing, but the default
eval operator is a very bad way to go about this.
const x = 1;
function evalAndReturnX(code) {
eval(code)
return x
}
console.log(evalAndReturnX("var x = 2"))
// 2
A less scary way to go about this is using the Function constructor. It takes
two arguments: a string containing a comma-seperated list of argument names and
a string containing the function body. It wraps the code in a function value so
that it gets it's own scope and wont do odd things with other scopes.
let plusOne = Function("n", "return n + 1;")
console.log(plusOne(4))
// 5