JS: eval
eval
eval(code_string)-
evaluate js code.
π WARNING: It is security risk to use eval. If you feed user input to eval, user may run arbitrary code.
console.log( eval("3 + 2") ) // 5 eval(`let x = 4 console.log( x ) `); // 4
eval tutorial
ai answer
eval in JavaScript is a built-in function that takes a string of JavaScript code and executes it as if it were actual code in the current scope.
Basic Syntax
eval(string)
- Parameter: A string containing JavaScript code.
- Returns: The result of the last expression evaluated (or
undefinedif nothing is returned).
Simple Examples
// Evaluate a simple expression console.log(eval("2 + 2")); // 4
// Declare variables eval("var x = 10;"); console.log(x); // 10 // does not work in modern js engine, due to use strict
// Run multiple statements eval(` let a = 5; let b = 10; console.log(a + b); `); // 15
// 4. Access local variables (it runs in the current scope) function test() { let secret = 42; eval("console.log(secret)"); } test(); // 42
How it Works Internally
evalparses the string as JavaScript source code.- It then executes that code in the current lexical scope (the same scope where
evalis called). - This means it can read and modify local variables, which is both powerful and dangerous.
Common Use Cases (rare nowadays)
- Dynamically generating and running code
- Implementing simple calculators or expression evaluators
- Legacy code that builds functions from strings
- Some metaprogramming tricks
Why eval is Almost Always a Bad Idea
| Problem | Explanation | Severity |
|---|---|---|
| Security | If the string comes from user input β code injection (Cross-Site Scripting (XSS) and Remote Code Execution (RCE)) | Critical |
| Performance | Code can't be optimized by the JS engine (no JIT benefits) | High |
| Debugging | Stack traces and source maps become useless | High |
| Scope pollution | Can unexpectedly create/modify variables in outer scopes | Medium |
| Strict mode issues | Behavior changes in "use strict" |
Medium |
| CSP | Content Security Policy often blocks eval entirely |
High |
Classic dangerous example:
// NEVER DO THIS const userInput = "alert('hacked'); // or worse..."; eval(userInput); // Runs arbitrary code
Safer Alternatives
| Goal | Better Alternative |
|---|---|
| Evaluate math expressions | new Function(...) or a math library (math.js) |
| Dynamic property access | Bracket notation: obj[key] |
| Parse JSON | JSON.parse() |
| Create functions dynamically | new Function('a', 'b', 'return a + b') |
| Template-based code | Template literals + careful construction |
| Sandboxed execution | vm module (Node.js) or iframes + postMessage |
Slightly safer version of eval (still not great):
// Creates a function in the global scope (doesn't see local vars) const result = new Function('return ' + expression)();
Strict Mode Behavior
"use strict"; eval("var y = 20;"); console.log(y); // ReferenceError: y is not defined // (in non-strict mode it would leak to the outer scope)
Summary
eval= βtake this string and run it as JavaScript right here.β- Extremely powerful β extremely dangerous.
- In modern JavaScript (ES6+), you almost never need it.
- Prefer
JSON.parse, bracket notation,new Function, or proper libraries instead.
Rule of thumb:
If you think you need eval, youβre probably wrong. There is almost always a cleaner, safer way.
Want me to show any specific example, comparison with new Function, or how to safely evaluate expressions?