The task is to create a function from the string given in the format of the function. Here are a few approaches that are listed below:
- Using Function() Constructor
- Using eval() Method
Approach 1: Using Function() Constructor
- Use the Function() Constructor to create a function from the string.
- It accepts any number of arguments (in the form of string). The last one should be the body of the function.
- In this example, Only the body of the function is passed, returning a value.
Example 1: This example implements the above approach.
Javascript
let func = 'return "This is return value";' ; // We can use 'func' as function function funFromString() { let func2 = Function(func); // Now 'func' can be used as function console.log(func2()); } funFromString(); |
This is return value
Approach 2: Using eval() Method
- Use the eval() method to create a function from the string.
- It accepts the function in the form of a string and converts it to a JavaScript function.
- In this example, It takes 2 arguments and returns the sum of both numbers.
Example 2: This example uses the approach discussed above.
Javascript
const str = "var func = function (a, b) { return a + b; };" ; // Till this point we can use 'func' as function function funFromString() { // Converting the string to function eval(str); console.log(func(2, 5)); } funFromString(); |
7