Last Updated: February 25, 2016
·
2.063K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside