Last Updated: February 25, 2016
·
1.814K
· ernestocodesnippets

eval() is evil

Yep eval() is evil, but what if we need to evaluate code from a string, and there is no other workaround?
Use a temporary function, like in the example:

var string = 'alert("eval is evil")';

// bad
eval(string);

// good
var tmpFunc = new Function(string);
tmpFunc();

// **same** result, less work for the interpreter, faster code, and more maintainable


Link to the example at jsFiddle:
http://jsfiddle.net/KuQu7/1/

An article on eval():
http://24ways.org/2005/dont-be-eval