Creating Functions Dynamically In JavaScript

Introduction

 
In this article, we’ll learn to create dynamic functions from strings on the fly.
 

Functions 101

 
A function is the fundamental building block in JavaScript. A function consists of a group of statements that performances a specific task. A function could accept input in form of parameters and produce output using the return statement.
 
Creating a function is quite straightforward. Primarily, there are two ways to create a function.
 
Function Declaration
  1. function square(num) {    
  2.     return num * num;    
  3. } 
As you can see in the above example square function accepts a single parameter called num and returns the square of that number
 
Function Expression
 
The above function declaration can be represented in form of expression as follows:
  1. const square = function(num) {    
  2.     return num * num;    
  3. }  
You could also use an arrow function to create a function expression:
  1. const square = function(num) {    
  2.     return num * num;    
  3. }
One thing we need to take into account is every function created in JavaScript is an instance of the Function object.
  1. function square(num) {    
  2.     return num * num;    
  3. }  
  4. console.log(square instanceof Function)  
  5. // output: true  
  1. const square = function(num) {    
  2.     return num * num;    
  3. }  
  4. console.log(square instanceof Function)  
  5. // output: true  
  1. const square = function(num) {    
  2.     return num * num;    
  3. }  
  4. console.log(square instanceof Function)  
  5. // output: true  

Creating The Dynamic Function

 
Syntax
 
The Function object can also be used as a constructor function to create a new function on the fly. The syntax for creating a function from Function Object is as follows:
  1. const myFunction = new Function(arg1, arg2, …argN, body);  
args1, args2,.. argsN are the arguments accepted by the function and body is the string consisting of JavaScript statements that will be executed when the function is called.
 
Examples
 
Let’s quickly understand this in detail with help of an example.
  1. const sq = new Function('num''return num * num');   
  2. sq(2); // output: 4
In the above code snippet, we’re creating a function that accepts a single parameter ‘num’ and returns the square of that number.
 
Let’s take a look at one more example. The following function accepts two parameters x and y and returns the result of the multiplication of those two numbers. 
  1. const multiply = new Function('x''y''return x * y');  
  2. multiply(2, 5); // output: 10 
It’s also possible to create a function that doesn’t accept any parameters.
  1. const logger = new Function('console.log("hello javascript")')  
  2. logger(); //output: hello javascript  
You could also write function body on multiple lines using es6 template literals.
  1. const square = new Function('numbers', `  
  2.     return numbers  
  3.             .map(num => num * num)  
  4. `);  
One thing to keep in mind is the functions created with new Function syntax are created in the global scope and will not be able to access the current lexical environment.
 
Hence, the function won’t be able to access variables from its outer lexical environment.
  1. function myFunc() {    
  2.   const num = 2;    
  3.     
  4.   const sq = new Function('return num * num');    
  5.     
  6.   return sq;    
  7. }     
  8.     
  9. myFunc()();  
  10. // output: Uncaught ReferenceError: num is not defined  
However, function declarations does have access to it’s outer environment.
  1. function myFunc() {  
  2.   const num = 2;  
  3.   
  4.   const sq = function() { return num * num }  
  5.   
  6.   return sq;  
  7. }   
  8.   
  9. myFunc()();  
  10. // output: 4  
This feature is rarely needed but could be unavoidable in certain situations. Imagine you’re building complex web-based applications and have stored logic in form of code on the server-side environment and wish to generate functions using that logic on the go.
 
One thing to note is apart from these rare situations creating dynamic functions should be avoided as they make the code prone to security and performance issues.
 

Summary

 
TLDR, The Function object could be used as a constructor function to create dynamic functions on the fly.
 
Syntax
  1. const myFunction = new Function(arg1, arg2, …argN, body);  
Examples
  1. const sq = new Function('num''return num * num');  
  2. sq(4); output: 16