Jan 20

JavaScript functions as strings as functions

In my second day at Catalyst, we did some programming koans, and I learned something really interesting– JavaScript, every function has a toString() and the Function constructor can create functions from strings.

Exploring the relationship between functions and strings

Let’s say we’ve already defined a function called “product” in the browser console:

We can see the string representation of our function by calling the toString() method:

Build functions from strings with new Function

This is where things start to get fun. First we’ll put the entire function body in a string, using \n\ to escape our new line. Then we pass the argument names and function body into the new Function constructor, each wrapped in strings. This creates a new function, named f, that returns the product of its arguments, just as product() does.

Continuing down the rabbit-hole

Strings can be sliced, modified, messed with to create other functions. By doing a substitution on the string, we can make a function that adds instead of multiplying.

The next step would be to create a function that takes a string as input and returns an array of strings– one string for each parameter and one for the function body. The two variable version of this is as follows:

The crazy function above parses the toString() of a function into arguments and a function body, wraps them in strings, passes them into a new anonymous function constructor and returns it. It is the inverse function of toString().

If JavaScript included some higher order functional tools like apply(), this crazy function could be extended to handle any arbitrary number of function arguments. Fortunately, these tools can be added to JavaScript without too much work.

If anybody has any experience using this feature for anything practical, I’d love to hear about it!

This entry was tagged , , .
Bookmark the permalink.

2 Responses to JavaScript functions as strings as functions

  1. John says:

    This is, I believe, a textbook perfect example of Greenspun’s 10th Rule :-D

  2. Pingback: Learning to Code: Week 36 – 100% Focus on Hack Reactor – Craig Rodrigues

Leave a Reply

Your email address will not be published. Required fields are marked *