eval()
is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval()
with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval()
was invoked (if it's a direct eval), which can lead to possible attacks in ways to which the similar Function
is not susceptible.
eval()
is also slower than the alternatives, since it has to invoke the JavaScript interpreter, while many other constructs are optimized by modern JS engines.
Additionally, modern JavaScript interpreters convert JavaScript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of eval()
will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. Additionally, new things can be introduced to that variable through eval()
such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate.
Fortunately, there's a very good alternative to eval()
: using the Function
constructor. Bad code with eval()
:
function looseJsonParse(obj) {
return eval(`(${obj})`);
}
console.log(looseJsonParse(
"{a:(4-1), b:function(){}, c:new Date()}"
))
Better code without eval()
:
function looseJsonParse(obj) {
return Function(`"use strict";return (${obj})`)();
}
console.log(looseJsonParse(
"{a:(4-1), b:function(){}, c:new Date()}"
))
The two code snippets above may seem to work the same way, but they do not; the eval()
one is a great deal slower. Notice c: new Date()
in the evaluated string. In the function without the eval()
, the object is being evaluated in the global scope, so it is safe for the browser to assume that Date
refers to window.Date()
instead of a local variable called Date
. However, in the code using eval()
, the browser cannot assume this. For example, in the following code, Date
in the evaluated string doesn't refer to window.Date()
.
function Date(n) {
return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0];
}
function looseJsonParse(obj) {
return eval(`(${obj})`);
}
console.log(looseJsonParse(
"{a:(4-1), b:function(){}, c:new Date()}"
))
Thus, in the eval()
version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called Date()
. This is incredibly inefficient compared to Function()
.
In a related circumstance, if you actually want your Date()
function to be called from the code inside Function()
, should you just take the easy way out and use eval()
? No! Never. Instead, try the approach below.
function Date(n) {
return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0];
}
function runCodeWithDateFunction(obj) {
return Function(`"use strict";return (${obj})`)()(
Date
);
}
console.log(runCodeWithDateFunction(
"function(Date){ return Date(5) }"
))
The code above may seem inefficiently slow because of the triple nested function, but let's analyze the benefits of the efficient method above:
- It allows the code in the string passed to
runCodeWithDateFunction()
to be minified. - Function call overhead is minimal, making the far smaller code size well worth the benefit
-
Function()
more easily allows your code to benefit from the possible performance improvements provided by "use strict";
- The code does not use
eval()
, making it orders of magnitude faster than otherwise.
Lastly, let's examine minification. With using Function()
as shown above, you can minify the code string passed to runCodeWithDateFunction()
far more efficiently because the function arguments names can be minified too as seen in the minified code below.
console.log(Function('"use strict";return(function(a){return a(5)})')()(function(a){
return"Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ")[a%7||0]}));
There are also additional safer (and faster!) alternatives to eval()
or Function()
for common use-cases.
The difference between eval()
and Function()
is that the source string passed to Function()
is parsed as function body, not as a script. There are a few nuances — for example, you can use return
statements in a function body but not in a script. In case you intend to parse the content as a script, using indirect eval and forcing strict mode can be another secure alternative.
function looseJsonParse(obj) {
return eval?.(`'use strict';(${obj})`);
}
console.log(looseJsonParse(
"{a:(4-1), b:function(){}, c:new Date()}"
))
This way, the code being evaluated does not have access to the local scope and cannot define global variables.