Skip to content
Related Articles
Open in App
Not now

Related Articles

How to create a function from a string in JavaScript ?

Improve Article
Save Article
  • Last Updated : 23 Jan, 2023
Improve Article
Save Article

The task is to create a function from the string given in the format of the function. Here are a few techniques discussed with the help of JavaScript. Approach 1:

  • Use the Function() Constructor to create a function from the string.
  • It accepts any number of arguments(in form of string. The last one should be the body of the function.
  • In this example, Only the body of the function is passed which is returning a value.

Example 1: This example uses the approach discussed above 

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP"></p>
<button onclick="GFG_Fun()">
    Click Here
</button>
<p id="GFG_DOWN"></p>
<script>
    var up = document.getElementById('GFG_UP');
    var down = document.getElementById('GFG_DOWN');
    var func = 'return "This is return value";';
    up.innerHTML =
    "Click on the button to create "+
    "function from string.<br>FUNCTION - '"
    + func + "'";
      
    // Till this point we can use 'func' as function.
    function GFG_Fun() {
        var func2 = Function(func);
    // Now 'func' can be used as function.
        down.innerHTML = func2();
    }
</script>

Output:

How to create a function from a string in JavaScript ?

How to create a function from a string in JavaScript ?

Approach 2:

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

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP"></p>
<button onclick="GFG_Fun()">
    Click Here
</button>
<p id="GFG_DOWN"></p>
<script>
    var up = document.getElementById('GFG_UP');
    var down = document.getElementById('GFG_DOWN');
    var str = "var func = function (a, b) { return a + b; };";
    up.innerHTML =
    "Click on the button to create "+
    "function from string.<br>FUNCTION - '" + str + "'";
      
    // Till this point we can use 'func' as function.
    function GFG_Fun() {
    // converting the string to function.
        eval(str);
        down.innerHTML = func(2, 5);
    }
</script>

Output:

How to create a function from a string in JavaScript ?

How to create a function from a string in JavaScript ?


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!