Home > Article > Web Front-end > When Should You Use `eval()` vs `new Function()` in JavaScript?
Are eval() and new Function() Interchangeable in JavaScript?
When working with strings containing JavaScript code, two functions commonly arise: eval() and new Function(). While both can execute code embedded in a string, they exhibit distinct characteristics and behavior.
eval() vs new Function(): The Key Differences
Understanding the Code Snippet
The code snippet you provided demonstrates the different behaviors of eval() and new Function():
<code class="javascript">var evaluate = function(string) { return eval('(' + string + ')'); } var func = function(string) { return (new Function( 'return (' + string + ')' )()); }</code>
Both functions evaluate the string "2 1" and return the result. However, if you modify the code to include a local variable "a" in the function, you will observe that eval() can access and modify the local variable, while new Function() will not.
Cautions and Best Practices
While eval() and new Function() offer convenient ways to execute dynamic code, they should be used cautiously:
In most cases, it is recommended to rely on established JavaScript language features for dynamic code execution, such as template literals or the Function constructor without new.
The above is the detailed content of When Should You Use `eval()` vs `new Function()` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!