How to useFunction() Constructor in Javascript

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


Output

This is return value

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

...