How to convert a string in to a function in JavaScript?

To convert a string into a function in JavaScript, the eval() method can be used. This method takes a string as a parameter and evaluates it as JavaScript code, which can include function definitions.

Syntax

eval(string);

Example: Converting String to Function

In the following example, a string contains a JSON object where the 'age' property holds a function as a string. Using eval(), we convert this string into an actual executable function.

<html>
<body>
<script>
   var string = '{"name":"Ram", "age":"function() {return 27;}", "city":"New jersey"}';
   var fun = JSON.parse(string);
   fun.age = eval("(" + fun.age + ")");
   document.write(fun.name + " " + "of Age" + " " + fun.age() + " " + "from city" + " " + fun.city);
</script>
</body>
</html>

Output

Ram of Age 27 from city New jersey

Alternative Method: Function Constructor

A safer alternative to eval() is using the Function constructor to create functions from strings:

<html>
<body>
<script>
   var functionString = "return 'Hello from string function!'";
   var myFunction = new Function(functionString);
   document.write(myFunction());
</script>
</body>
</html>

Output

Hello from string function!

Security Considerations

Using eval() can be dangerous as it executes any JavaScript code, potentially including malicious scripts. The Function constructor is generally safer for creating functions from strings as it doesn't have access to local variables.

Conclusion

While eval() can convert strings to functions, consider using the Function constructor for better security. Always validate input strings before converting them to executable code.

Updated on: 2026-03-15T23:18:59+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements