How to create a function from a string in JavaScript?


Creating a function from a string in JavaScript can be helpful in situations when you need to generate a function dynamically at runtime or when you have a string that contains the code for a function you wish to execute.

The ability to construct a function from a string is a useful functionality of JavaScript that allows dynamic function creation at runtime. The eval() function and the new Function() function Object() [native code] are the two most popular methods for doing this, although both have significant security flaws.

The Function.prototype.constructor is a safer option even though it is less well known. It's crucial to consider the risks and use cases before choosing the JavaScript method for creating a function from a string.

Approach 1: Using the eval() Function

The JavaScript eval() method is one of the easiest ways to build a function from a string. This strong eval() function can run any JavaScript code that is supplied to it as a string.

Example

<html>
<body>
   <p id="result"></p>
   <script>
      let functionString = "function add(a, b) { return a + b; }";
      let add = eval("(" + functionString + ")");
      document.getElementById("result").innerHTML = "Sum of 1 and 2: " + add(1, 2);
   </script>
</body>
</html>

Here we can see, we have a function which takes two parameters and returns their sum. Now, this function is contained in a string. The eval() function receives this string as a parameter and evaluates it before returning the function. The returned function is then assigned to a variable called add, which can be used just like any other function.

However, it runs any JavaScript code that is provided to it, and hence using it in production code can be risky as it may result in security flaws.

Approach 2: Using the new Function() Constructor

Another way to create a function from a string in JavaScript is to use the Function() constructor. The Function() constructor creates a new function object from a string containing the code for the function. Here's an example of how to use the Function() constructor to create a function from a string −

Example

<html>
<body>
   <p id="print"></p>
   <script>
      let functionString = "function add(a, b) { return a + b; }";
      let functionBody = functionString.substring(
         functionString.indexOf("{") + 1,
         functionString.lastIndexOf("}")
      );
      let add = new Function("a", "b", functionBody);
      document.getElementById("print").innerHTML = "Sum of 1 and 2: " + add(1, 2);
   </script>
</body>
</html>

In this example, we pass the string containing the code for the function to the Function() constructor, which creates a new function object from that string. We then assign the returned function to a variable add, which can be used like any other function.

As it can only create functions, it is less risky than eval() but still carries a similar risk

Approach 3: Using the Function.prototype.constructor

This generates a function and can't run any other code than the function body passed as a string. However, it's less widely used and not as well supported by older browsers as the other two methods.

Example

<html>
<body>
   <p id="result"></p>
   <script>
      let add = Function.prototype.constructor('a', 'b', 'return a+b')(1, 2);
      document.getElementById("result").innerHTML = "Sum: " + add;
   </script>
</body>
</html>

In this example, function parameters and function body are provided to the constructor. We use the Function.prototype.constructor to create a new function with the given parameters and the given function body and then immediately call that function by invoking it with the given arguments

Remember that a function you construct from a string will have access to the global scope and will not be contained within the scope of the code you created it with.

Another important thing to keep in mind is that creating a function from a string could slow down the application, particularly if the function body is lengthy.

Moreover, building a function from a string can make it more challenging to understand and debug the code if the function is complex.

It is generally not recommended to use the eval() and new Function() methods in production code due to their security issues. Instead, you should consider other options, such as precompiling the function or using a JavaScript preprocessor such as Babel to transpile your code to an equivalent, safer version.

Updated on: 02-Mar-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements