eval() versus new Function()

eval and new Function are both ways to evaluates code dynamically in javascript.

Obviously,new Function has a much clearer interface and should be the preferred way of doing this task.

An easily neglected difference is that new Function execute in the global scope only, which means it won't create a closure. (window.eval also execute in the global scope)

You might think using this trait can eliminate some heavy memory usage closure. Actually, if the variable to be captured in the closure will not be used, it won't be captured (At least in V8). So, thanks to modern JS engines, no need to do those tedious replacement..

image