Open In App

How to create a function from a string in JavaScript ?

Last Updated : 25 Jul, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

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.


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. 


Output
7

Next Article

Similar Reads