Why is eval dangerous?
The eval() function is one of the most "dangerous" and controversial functions in JavaScript.
Let's break down in detail what it does, why it is often avoided, and what to replace it with.
What eval() does
eval() executes a string of JavaScript code as a program.
eval("console.log('Hello from eval!')");Output:
Hello from eval!Essentially, eval() takes a string and makes the JavaScript engine run it as regular JS code.
Examples of using eval()
Example 1: evaluating an expression
const x = 10;
const y = 5;
console.log(eval("x + y")); // 15eval "understands" that the string "x + y" is an expression, and returns the result.
Example 2: creating variables (dangerous)
eval("var z = 100;");
console.log(z); // 100The problem: the variable z is created in the current scope,
and it can overwrite existing values.
Example 3: dynamic code (bad practice)
function runCode(code) {
eval(code);
}
runCode("alert('Running arbitrary code')");This runs any code passed to it as a string. If that code came from a user, it can lead to an XSS attack or a full takeover of the application.
Why eval() is not recommended
Here are the main reasons:
1. A security risk (XSS, injections)
const userInput = "alert('Hacked!')";
eval(userInput); // runs right in the browser!This is a direct path to XSS attacks and data leaks.
2. Reduced performance
Code inside eval() runs slower,
because the JS engine cannot optimize it (it does not know in advance what is there).
Every call to eval() forces the engine to re-analyze and re-interpret the code string.
3. It breaks scope
Code inside eval() can create or change variables of the current context,
which makes the code unpredictable and hard to debug.
let a = 10;
eval("a = 99;");
console.log(a); // 99, the value changed "from the inside"4. It reads poorly and is hard to maintain
eval() makes the code magical and unpredictable:
it is unclear exactly what will run until the string is passed in.
Safe alternatives to eval()
| Task | What to replace it with |
|---|---|
| Evaluate a math expression | Function() or a ready-made parser (for example, math.js) |
| Convert JSON | JSON.parse() |
| Run dynamic code from functions known in advance | An object mapping to functions |
| Get a property by name | obj[propName], not eval("obj." + propName) |
Examples of replacement
Bad:
eval("user.name = 'Oleh'");Good:
user["name"] = "Oleh";Bad:
const obj = eval("(" + jsonStr + ")");Good:
const obj = JSON.parse(jsonStr);Bad:
eval("sum(5, 10)");Good:
const actions = { sum: (a, b) => a + b };
actions["sum"](5, 10);The short way to remember it
| What it does | Runs a string as JS code |
|---|---|
| Security | Very dangerous: XSS and injections |
| Performance | Slow |
| Debugging | Hard |
| Optimization | Blocks the JIT |
| Should you use it | Only in extremely rare cases, when you fully control the string |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.