Thursday, September 25, 2025
HomeLanguagesJavascriptHow to create a function from a string in JavaScript ?

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

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


Output

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


Output

7

RELATED ARTICLES

Most Popular

Dominic
32319 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6682 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6794 POSTS0 COMMENTS
Ted Musemwa
7070 POSTS0 COMMENTS
Thapelo Manthata
6753 POSTS0 COMMENTS
Umr Jansen
6761 POSTS0 COMMENTS