Using direct eval()
suffers from multiple problems:
-
eval()
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, allowing third-party code to access the scope in which eval()
was invoked (if it's a direct eval) can lead to possible attacks that reads or changes local variables. -
eval()
is slower than the alternatives, since it has to invoke the JavaScript interpreter, while many other constructs are optimized by modern JS engines. - 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. - Minifiers give up on any minification if the scope is transitively depended on by
eval()
, because otherwise eval()
cannot read the correct variable at runtime.
There are many cases where the use of eval()
or related methods can be optimized or avoided altogether.
Using indirect eval()
Consider this code:
function looseJsonParse(obj) {
return eval(`(${obj})`);
}
console.log(looseJsonParse("{ a: 4 - 1, b: function () {}, c: new Date() }"));
Simply using indirect eval and forcing strict mode can make the code much better:
function looseJsonParse(obj) {
return eval?.(`"use strict";(${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 first one using direct eval suffers from multiple problems.
- It is a great deal slower, due to more scope inspections. Notice
c: new Date()
in the evaluated string. In the indirect eval version, the object is being evaluated in the global scope, so it is safe for the interpreter to assume that Date
refers to the global Date()
constructor instead of a local variable called Date
. However, in the code using direct eval, the interpreter cannot assume this. For example, in the following code, Date
in the evaluated string doesn't refer to window.Date()
.
function looseJsonParse(obj) {
function Date() {}
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()
. - If not using strict mode,
var
declarations within the eval()
source becomes variables in the surrounding scope. This leads to hard-to-debug issues if the string is acquired from external input, especially if there's an existing variable with the same name. - Direct eval can read and mutate bindings in the surrounding scope, which may lead to external input corrupting local data.
- When using direct
eval
, especially when the eval source cannot be proven to be in strict mode, the engine — and build tools — have to disable all optimizations related to inlining, because the eval()
source can depend on any variable name in its surrounding scope.
However, using indirect eval()
does not allow passing extra bindings other than existing global variables for the evaluated source to read. If you need to specify additional variables that the evaluated source should have access to, consider using the Function()
constructor.
Using the Function() constructor
The Function()
constructor is very similar to the indirect eval example above: it also evaluates the JavaScript source passed to it in the global scope without reading or mutating any local bindings, and therefore allows engines to do more optimizations than direct eval()
.
The difference between eval()
and Function()
is that the source string passed to Function()
is parsed as a function body, not as a script. There are a few nuances — for example, you can use return
statements at the top level of a function body, but not in a script.
The Function()
constructor is useful if you wish to create local bindings within your eval source, by passing the variables as parameter bindings.
function Date(n) {
return [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
][n % 7 || 0];
}
function runCodeWithDateFunction(obj) {
return Function("Date", `"use strict";return (${obj});`)(Date);
}
console.log(runCodeWithDateFunction("Date(5)"));
Both eval()
and Function()
implicitly evaluate arbitrary code, and are forbidden in strict CSP settings. There are also additional safer (and faster!) alternatives to eval()
or Function()
for common use-cases.
Using bracket accessors
You should not use eval()
to access properties dynamically. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with eval()
:
const obj = { a: 20, b: 30 };
const propName = getPropName();
const result = eval(`obj.${propName}`);
However, eval()
is not necessary here — in fact, it's more error-prone, because if propName
is not a valid identifier, it leads to a syntax error. Moreover, if getPropName
is not a function you control, this may lead to execution of arbitrary code. Instead, use the property accessors, which are much faster and safer:
const obj = { a: 20, b: 30 };
const propName = getPropName();
const result = obj[propName];
You can even use this method to access descendant properties. Using eval()
, this would look like:
const obj = { a: { b: { c: 0 } } };
const propPath = getPropPath();
const result = eval(`obj.${propPath}`);
Avoiding eval()
here could be done by splitting the property path and looping through the different properties:
function getDescendantProp(obj, desc) {
const arr = desc.split(".");
while (arr.length) {
obj = obj[arr.shift()];
}
return obj;
}
const obj = { a: { b: { c: 0 } } };
const propPath = getPropPath();
const result = getDescendantProp(obj, propPath);
Setting a property that way works similarly:
function setDescendantProp(obj, desc, value) {
const arr = desc.split(".");
while (arr.length > 1) {
obj = obj[arr.shift()];
}
return (obj[arr[0]] = value);
}
const obj = { a: { b: { c: 0 } } };
const propPath = getPropPath();
const result = setDescendantProp(obj, propPath, 1);
However, beware that using bracket accessors with unconstrained input is not safe either — it may lead to object injection attacks.
Using callbacks
JavaScript has first-class functions, which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write:
setTimeout(() => {
}, 1000);
elt.addEventListener("click", () => {
});
Closures are also helpful as a way to create parameterized functions without concatenating strings.
Using JSON
If the string you're calling eval()
on contains data (for example, an array: "[1, 2, 3]"
), as opposed to code, you should consider switching to JSON, which allows the string to use a subset of JavaScript syntax to represent data.
Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.
Passing carefully constrained data instead of arbitrary code is a good idea in general. For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in XPath instead of JavaScript code.