
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert String to 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.
<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
Advertisements