Hiprup

What is eval() and why should you avoid it?

eval() executes a string as JavaScript code. It's powerful but strongly discouraged.

  • Security — running strings can execute malicious code (a major injection risk).

  • Performance — it blocks engine optimisations and is slow.

  • Debugging — code hidden in strings is hard to read and maintain.

Almost always avoidable: use objects/maps for dynamic lookup, or JSON.parse for data.

// DANGEROUS — never do this with user input
const userInput = 'alert("hacked!")';
eval(userInput); // Executes arbitrary code!

// Alternative: JSON.parse (safe)
const jsonStr = '{"name": "John", "age": 30}';
const data = JSON.parse(jsonStr); // Safe — only parses JSON

// Alternative: Function() (isolated scope)
const fn = new Function('a', 'b', 'return a + b');
console.log(fn(2, 3)); // 5 — no access to local variables

// Alternative: dynamic property access
const prop = 'name';
// eval('obj.' + prop); // BAD
const value = obj[prop]; // GOOD — bracket notation

eval executes any string as code — massive security risk with user input. JSON.parse only parses valid JSON (safe).

Function() creates a function in the global scope (no access to local variables — safer than eval). Bracket notation (obj[prop]) replaces eval for dynamic property access.

Know three reasons to avoid eval: security (code injection), performance (disables optimization), and scope pollution. Show three alternatives: JSON.parse (data), Function() (isolated execution), bracket notation (dynamic properties). 'eval is evil' is the common saying.

What is eval() and why should you avoid it? | Hiprup