How to useeval() Method in Javascript

  • 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();


Output

7


How to create a function from a string in JavaScript ?

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

Similar Reads

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....

Approach 2: Using eval() Method

...