eval vrs. new Function

It's not often a good idea to evaluate text as code, but sometimes it is necessary. There are two ways to do it in JavaScript, eval and new Function. They are subtly different. Neither are safe, but new Function has less possible side effects.

a = 10 console.log( bar('a + 2') ) // 3 function bar (txt) { var a = 1; return eval(txt) }

At first glance it's hard to tell what is going to happen when you eval the txt. The 'a' is surprisingly the scope inside the function where the eval happens, not the global a outside. It exposes the internal state of the function to the person passing in the string, sometimes surprisingly to both the caller and the callee.

a = 10 console.log( bar('a + 2') ) // 12 function bar (txt) { var a = 1; return new Function('return ' + txt)() }

Ahh, there we go, our new function doesn't see the internal variable, only the global value! Much more predictable behavior than evaling the same text.

Now, remember don't use either if you can possibly avoid it. But, if you really need to, prefer new Function to eval.