How to create a function from a string in JavaScript ?


In JavaScript, we can create a function from a string using the Function() constructor or the eval() function. Here are the examples of both methods:

  • Using the Function() constructor:

The Function() constructor creates a new function object from a string of code. The syntax for using the Function() constructor is as follows:

const myFunction = new Function(arg1, arg2, ..., functionBody);

Here, arg1, arg2, etc. are the arguments that the function takes, and functionBody is the string of code that defines the function. For example:

const myFunction = new Function('a', 'b', 'return a + b;');
console.log(myFunction(2, 3)); // Output: 5

In this example, we create a new function that takes two arguments a and b, and returns their sum. We then call the function with arguments 2 and 3, which returns 5.

  • Using the eval() function:

The eval() function evaluates a string of code as JavaScript code and returns the result. We can use the eval() function to create a function from a string as follows:

const myFunction = eval('(function(a, b) { return a + b; })');
console.log(myFunction(2, 3)); // Output: 5

In this example, we create a new function that takes two arguments a and b, and returns their sum using an anonymous function. We then pass the string representation of the function to the eval() function, which evaluates it as JavaScript code and returns the function object. We then call the function with arguments 2 and 3, which returns 5.

Note: The use of eval() is generally discouraged due to security concerns, as it can execute arbitrary code and potentially introduce vulnerabilities in your application. It is recommended to use the Function() constructor instead.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.