Hint
Create functions from strings at runtime — dynamic but slower, eval-like risks, no closure
// Syntax: new Function([...params], functionBody)
const add = new Function('a', 'b', 'return a + b');
add(2, 3); // 5
const greet = new Function('name', 'return "Hello, " + name');
greet('Alice'); // 'Hello, Alice'
// Key characteristic: no closure — runs in GLOBAL scope
const x = 10;
function test() {
const x = 20; // local x
const fn = new Function('return x'); // does NOT close over local x
return fn();
}
test(); // 10 (global x) — NOT 20!
// Use cases (rare):
// 1. Dynamic code from server (CMS, user-defined formulas)
const formula = new Function('a', 'b', serverSideFormula);
// 2. Template engines (pre-compile to JS)
// 3. Sandboxed evaluation (safer than eval)
const fn = new Function('data', 'with(data) { return x + y }');
fn({ x: 1, y: 2 }); // 3 (limited scope)
Risks and drawbacks: Cannot access local scope (can't make closures). Security risk if body comes from user input. Blocks V8 optimization. Slower than regular functions.