Lesson 52: Mastering JavaScript "new Function" syntax with challenges!
What is new Function?
Itβs a way to dynamically create a new function from strings at runtime.
π© Syntax:
let func = new Function([arg1, arg2, ...argN], functionBody);
Each argument and the body are passed as strings.
Returns a new function.
let sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 3)); // 5
π§ Key Insight:
Unlike normal functions, a function created with new Function does not close over the outer lexical environment β it closes over the global environment only.
π₯ Example with Closure Difference:
jsCopyEditfunction getFunc() {
let secret = "hidden";
return new Function('console.log(secret)');
}
getFunc()(); // β ReferenceError: secret is not defined
But with a regular function:
function getFunc() {
let secret = "hidden";
return function() {
console.log(secret); // β
works
}
}
getFunc()(); // "hidden"
πΉ 2. Fill Any Gaps
β Hidden Concepts and Advanced Mechanics
β
[[Environment]] Internal Slot
Every function in JS has a hidden [[Environment]] β itβs the lexical scope captured at creation time.
function()or arrow functions: capture current[[Environment]].new Function(...): always captures global environment.
π₯ This means variables in outer scopes are inaccessible to
new Function.
β Quirks / Gotchas
𧨠1. Lack of Closure
let user = "Manoj";
let f = new Function('console.log(user)');
f(); // β ReferenceError
𧨠2. Eval-like behavior
Using new Function is similar to eval():
It compiles code at runtime
Avoids capturing local scope
May be blocked in CSP (Content Security Policy)
𧨠3. Minifier Breakage Prevention
Minifiers rename local vars. If dynamic function creation accessed them, code could break post-minification.
𧨠4. No access to this unless explicitly passed
You must bind or pass this to use it inside:
let f = new Function('return this.value');
console.log(f.call({ value: 42 })); // 42
β Browser Differences & Security
β οΈ In CSP-restricted environments (
script-src 'self'),new Functionthrows.Chrome & Firefox treat it as unsafe in extensions.
Many JS linters warn against it.
πΉ 3. Challenge Me Deeply
π’ Basic
Create a function using
new Functionthat multiplies two numbers.Create a
new Functionthat alerts "Hello World" but does not take any parameters.Write a
new Functionthat accepts a parameter and returns its square.
π‘ Intermediate
Dynamically build a function that validates if a string contains a keyword (keyword is passed at runtime).
Write a factory function that returns a new function based on a user-defined mathematical operation (
+,-,*,/).Use
new Functionto implement a simple calculator:"3 * 5 + 2"β17.
π΄ Advanced
Create a dynamic form validator that builds a custom validation function from string rules.
Use
new Functionin a way that bypasses a minifier's renaming of a parameter.Construct a sandboxed execution system using
new Functionfor plugin-like logic (no closures, secure).Build a code runner for user-written code snippets that canβt access internal app state.
π― Brain Twister
- Why does this fail?
function outer() {
let secret = "top-secret";
return new Function('return secret;');
}
console.log(outer()()); // ??
πΉ 4. Interview-Ready Questions
β Conceptual
What is the difference between
eval()andnew Function()?Why does
new Function()not capture local variables?What are the performance and security implications of using
new Function()?
β Debugging
A developer dynamically creates a function using
new Function, but it can't access variables in their module β why?You minified your JS app and now dynamic code that worked before fails β what happened?
β Scenario-Based
You receive rules from a backend as strings and need to validate input β how would you do it safely?
If you use
new Functionin a browser extension, what are the security/CSP considerations?
β Best Practices
π Impressive:
Avoiding
new Functionunless dynamic runtime code is truly neededUsing factory functions instead when closures are required
Sanitizing any string input used in dynamic function creation
π Red Flags:
Using
new Functionjust to delay logicPassing user input unsanitized β XSS vulnerability
Using it in code meant to run in restricted environments
πΉ 5. Real-World Usage
β Where it's used:
Form builders: Build field validation dynamically from schema
Template engines: Compile template into JS function (e.g., Handlebars precompilation)
No-code platforms: Let users write formula expressions that become executable code
Game engines: Allow scripted logic from external files
β Examples
π Lodash (older versions)
_.template('Hello <%= name %>') // compiles to a function
π§© Vue / Angular templates
Older template compilers would optionally allow using new Function.
πΉ 6. Remember Like a Pro
π§ Mnemonic:
"New Function = New Scope (Global Only)"
NFGS β New Function = Global Scope
β‘ Analogy:
new Functionis like loading code from a script tag written at runtime β it doesnβt βseeβ where it came from, only whatβs in the global world.
π§Ύ Cheatsheet:
| Feature | function/arrow | new Function |
| Scope Captured | Local | Global only |
| Closure Access | β Yes | β No |
| Minifier Safe | β Risk | β Safe |
| Security Risk | Medium | High (CSP risk) |
| Code as String? | β | β Yes |
| CSP-compatible | β | β Often blocked |
πΉ 7. Apply It in a Fun Way
π§ͺ Mini Project: Dynamic Math Evaluator (like a custom calculator)
π¦ Goal:
Create a tool where users type something like "a + b * 2" and get a compiled function they can reuse.
π Steps:
Create a function
buildEvaluator(expr: string)that returns a function.Use
new Function('a', 'b', 'return ' + expr)inside.Let users provide
aandbvalues and see results.Prevent code injection by sanitizing expr (e.g. only allow digits, variables,
+ - * /).
π Extension Ideas:
Allow variables from a list, like
x, y, zAdd safe mode using regex to disallow harmful keywords (
document,eval, etc.)Support functions like
Math.sqrt,Math.pow
β Bonus
π§° Open-Source Projects Using This Heavily
Lodash (
_.template)AngularJS $compile (legacy)
jQuery Templates (deprecated)
FormIO β dynamic form validation rules
π¨ Common Developer Mistakes
Thinking
new Functioncan access outer scope (it canβt)Using unsanitized strings from users (XSS)
Not understanding CSP violations (production error)
Assuming it's "better" than closures β it's not unless needed
π Performance Tips
new Functionhas high creation cost β avoid in hot pathsPrefer regular functions or closures if dynamic behavior isn't essential
Use caching if building many similar dynamic functions
β Deprecated or Modern Alternatives?
β Use
Functiononly when runtime compilation is needed.β Use closures and factory functions instead where possible.
β Use Web Workers or module loaders to isolate dynamic logic.
π§ Summary Table
| Concept | Details |
| Function Scope | Global only |
| Lexical Env Closure | β No β unlike regular functions |
| Creation Style | String-based |
| Use Cases | Templating, evaluators, plugin systems |
| Risks | XSS, CSP violations, performance |
| Alternatives | Factory functions, closures, arrow functions |