Suggest an editImprove this articleRefine the answer for “Why is eval dangerous?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**`eval()`** executes a string of JavaScript code as a program, which makes it one of the most "dangerous" and controversial functions in the language. **Key point:** `eval()` can run any code passed to it, including malicious code, which is a direct path to XSS attacks and data leaks.Shown above the full answer for quick recall.Answer (EN)ImageThe `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**. ```javascript eval("console.log('Hello from eval!')"); ``` Output: ```javascript 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 ```javascript const x = 10; const y = 5; console.log(eval("x + y")); // 15 ``` `eval` "understands" that the string `"x + y"` is an expression, and returns the result. --- ### Example 2: creating variables (dangerous) ```javascript eval("var z = 100;"); console.log(z); // 100 ``` The problem: the variable `z` **is created in the current scope**, and it can **overwrite** existing values. --- ### Example 3: dynamic code (bad practice) ```javascript 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) ```javascript 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. ```javascript 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: ```javascript eval("user.name = 'Oleh'"); ``` #### Good: ```javascript user["name"] = "Oleh"; ``` --- #### Bad: ```javascript const obj = eval("(" + jsonStr + ")"); ``` #### Good: ```javascript const obj = JSON.parse(jsonStr); ``` --- #### Bad: ```javascript eval("sum(5, 10)"); ``` #### Good: ```javascript 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 |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.