Software Development

JavaScript – Convert Function to String and Back

This post demonstrates how to convert a JavaScript function to a string and using the same string to declare and execute a new method dynamically.

Using Plunker

Plunker is an online website that allows programmers to create client-side JavaScript code snippets for demonstration, issue replication, or Proofs-of-Concept (POCs).

My Plunker

To access my JavaScript code snippet available on Plunker, please access the following URL:

https://plnkr.co/G4nQ4n50JB1dWF5NCLQu

Notice the contents under the Console tab on the right side. First, the function’s definition is displayed. Then, that definition is used twice displaying “This is myFunction” twice.

There are 2 important files to get things working.

  • index.html
  • script.js

By the way, I am using Google Chrome to access Plunker.

Using Node.js

Node.js allows you to create and execute server-side codes. We’ll not discuss Node.js but I assume you have it installed in your system.

Download the script.js from my Plunker, and run it on the Windows command-line prompt.

The JavaScript Code Snippet

The script.js file used in both Plunker and Node.js has the following codes.

Code to Convert a Function to String

To convert a function to string, use the toString() method of a function object.

Codes to convert string to a function

 

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like