Module 48 // Core JavaScript

eval & Dynamic Code Execution

Module Objective

Security risks, scope behavior, safer alternatives

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Dynamic Math Parsing
const expression = "2 + 2";
const result = eval(expression);

console.log(result); // 4
💡 Eval can turn any string into live code. However, if the string comes from a user, they could run malicious scripts like `window.location = ...`.
// Example 2
// 2. The Scope Trap
let x = 10;
function demo() {
  let x = 20;
  eval("x = 30"); // Which 'x' is changed?
  console.log(x); // 30
}

demo();
console.log(x); // 10
💡 Standard `eval()` uses the **Local Scope** where it was called. This makes code hard to optimize because the engine can't predict what variables will change.
// Example 3
// 3. Global eval
// Use indirect call to force global scope
const globalEval = eval;
globalEval("var globalLeak = 1");
💡 Indirect eval (calling it via a variable) forces the code to run in the Global Realm, preventing it from touching local variables.

Engine & Memory Architecture

The Parser Cost

1. No Optimizations:

  • When the engine sees eval(), it must disable the JIT Compiler for that entire function.
  • The engine cannot assume anything about local variables, making execution significantly slower in RAM.

2. Dynamic Parsing:

  • Every eval() call triggers the Full Parser and Bytecode Generator.
  • This is a heavy CPU operation that would normally only happen once when the script loads.

3. Memory Bloat:

  • Dynamically created functions stay in the Heap even after the execution finishes, potentially leading to memory leaks if called in a loop.