JS: eval

By Xah Lee. Date: . Last updated: .

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)

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

Common Use Cases (rare nowadays)

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

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?