News for hackers. Stuff that matters.
Re:JavaScript Garden by grayrest on Wednesday January 14, 2015 @07:43AM (#8885853)
> The conclusion doesn't offer any advise what should be done instead of eval.

In case anybody is actually wondering, you almost always want a Function constructor:

    var add = new Function('arg1', 'arg2', 'return arg1 + arg2;');
The only exception I've ever run into was in miniature string templating where eval or with was used as a hacky way to generate the context. The best way to do that is replace with a function argument:

    tmpl_str.replace(/{{(\w+)}}/g, function(_, key) { return ctx[key]; })
Re:JavaScript Garden by arnarbi on Wednesday January 14, 2015 @10:58AM (#8887028)
> In case anybody is actually wondering, you almost always want a Function constructor

I don't see how that's any different from eval.

What you almost always want is a better abstraction of your data and operations, that allows you to stop treating data as code.

Re:JavaScript Garden by babablacksheep on Wednesday January 14, 2015 @08:18AM (#8886005)
new Function() parses the JavaScript code stored in a string into a function object, which can then be called. It cannot access local variables because the code runs in a separate scope.
Re:JavaScript Garden by LunaSea on Wednesday January 14, 2015 @10:17AM (#8886721)
Function constructor as well as setInterval() and setTimeout() with stringyfied functions are almost as insecure as eval().

Until now I don't think that I have ever encountered a case where any of these were the absolute only solution.