Function Constructor (Rarely Used)
You'll learn about a mostly obsolete way to create functions and why modern JavaScript avoids it.
JavaScript provides a built-in Function constructor that creates functions from strings at runtime. While technically possible, it's considered poor practice and should almost never be used.
How It Works
The Function constructor takes string arguments: the last string is the function body, and all preceding strings are parameter names:
const add = new Function('a', 'b', 'return a + b;');
console.log(add(2, 3)); // 5
You can also pass everything as one string:
const greet = new Function('name', 'return "Hello, " + name;');
console.log(greet('Alice')); // "Hello, Alice"
Why It's Avoided
Security risks: Creating functions from strings is similar to eval() — it can execute arbitrary code, making your application vulnerable if the strings come from user input.
Performance: These functions are harder for the JavaScript engine to optimize because they're created at runtime.
No closure access: Unlike normal functions, Function constructor functions don't capture their surrounding scope — they only see global scope.
Readability: Code-as-strings is harder to read, debug, and maintain. Your editor can't provide syntax highlighting or catch errors.
When You'd See It
Extremely rare cases like building dynamic code generators or template systems, but even then, better alternatives exist (like actual template literals or proper parser libraries).
Key Takeaway: The Function constructor creates functions from strings but is almost never appropriate due to security risks, performance issues, and lack of closure access—stick to normal function declarations and expressions instead.