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


To convert a string in to function "eval()" method should be used. This method takes a string as a parameter and converts it into a function.

syntax

eval(string);

Example

In the following example, in a string itself, a property called 'age' is assigned with a function. Later on, using eval() function the property age is converted into a function and displayed as shown in the output.

 Live Demo

<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

Updated on: 29-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements