Matt Snider JavaScript Resource

Understanding JavaScript and Frameworks

Saturday, June 28, 2008

Functional JavaScript

Most of the time my focus is on OOP JavaScript, and I provide very little discussion of functional JavaScript. This is because although JavaScript is not a traditional OOP language, it is an OOP language (a ‘prototype’ based one). I prefer to leverage the OOP structure of the language, however JavaScript is very versatile and you are not limited to one coding style. Functional programming is one of these styles, it is a technique where one uses global methods to manipulate basic data structures, such as strings, integers, objects, etc. (PHP < v5 is a good example of a function-driven programming language).

Consider for example the 'trim' method that removes the surrounding whitespace from strings. Many developers and libraries choose to add ‘trim’ to the ‘prototype’ of the String Object:

Example 1: Prototype-Based Trim

String.trim = function() { return this.remove(\/^\\s\\s*\/).remove(\/\\s\\s*$\/); };

In functional programming one would write the same function as follows:

Example 2: Functional Trim

string_trim = function(str) { return str.remove(\/^\\s\\s*\/).remove(/\\s\\s*$\/); };

The work of the method hasn’t changed; we are still doing two regular expression removes on a String. However the method structure has. First, because we are putting the method in the global namespace, we need to use a naming convention. In example 2, I have used the naming convention, nameOfObject + ‘_’ + nameOfFunction, with the first letter of each part lower-case, and all subsequent words camel-case (not shown in example, since ‘trim’ is a single word). The Object name is used as a prefix, because you may have multiple ‘trim’ functions (perhaps an ‘array_trim’ that removes empty elements from an Array). Also, in Example 2, we pass the String Object into the Function instead of referencing ‘this’ as done in Example 1.

Those are the two major differences between Functional and OOP programming in JavaScript. In OOP you will extend ‘prototype’ and your methods will directly reference the instantiated Object with the ‘this’ keyword. In Functional JavaScript you will call global methods and pass primitive objects around, ideally never need to the ‘this’ keyword.

My initial thoughts on Functional JavaScript produced these considerations:

Functional JavaScript will be slower than OOP
This is probably just a knee-jerk reaction, because I don’t see why this would be true. Functions are executed quickly in JavaScript, whether attached to an Object or referenced by a closure. It is true that you will use slightly fewer characters using the OOP method, because the names of the functions are generally shorter. However, we attach fewer methods to primitive objects with the Functional method, so each primitive Object instantiation will be faster and lighter.
Functional JavaScript will have namespace conflicts
While this could be an issue, with a good naming convention it can be easily avoided. I recommend extending the method used in Example 2 to also include the author’s initials (nameOfObject + ‘_’ + authorsInitials + ‘_’ + nameOfFunction). This naming convention allows you to have multiple methods for the same operation, in-case you needed that. And also gives the JavaScript community an idea of the author of a given method.
What About the Module Pattern and encapsulation
While, you won’t be able to leverage all the goodness of the module pattern, because true Functional JavaScript will not return an instance of ‘this’, as the module pattern does. You still can benefit from the use of anonymous functions to encapsulate your business logic and avoid local namespace conflicts.
Are there Frameworks written for Functional JavaScript
As far as I know, there are none. I would be interested in seeing how effective this pattern works on the library level. However, it would be a colossal undertaking.

I do not believe there is a drastic performance improvement with either technique; however one would need two comparable libraries using the different techniques and run many tests against each to verify this. I believe the decision on whether you use Functional or OOP JavaScript comes down to your own coding preference and whether you want to use an existing framework or not.

Peter Michaux also wrote a good article about JavaScript Namespacing, if you are interested in additional reading. If you have experience with Functional JavaScript libraries and would like to share, please post a comment.

posted by Matt Snider at 12:37 am  

7 Comments »

  1. What you describe is not exactly what Functional Programming means in general usage. See wikipedia:
    http://en.wikipedia.org/wiki/Functional_programming

    I don’t think you will find many people willing to agree that PHP is a functional language. Functions aren’t first-order objects in PHP, so you can’t use functions as data - a basic technique in functional programming.

    A library for functional programming in JS:
    http://osteele.com/sources/javascript/functional/
    Function currying in JS:
    http://www.svendtofte.com/code/curried_javascript/

    Comment by Lon — June 28, 2008 @ 9:55 am

  2. A primary difference between the functional and OOP styles is the lack or use of mutable state. In pure functional programming a function takes parameters and does not mutate them but rather the interesting part is the function returns a result. In OOP an object frequently has mutable state which is mutated when methods are called on that object. There are many areas of grey to be explored here.

    Polymophism seems to be an important problem with the functional style in JavaScript. If I have a heterogeneous array of string and array objects, and each object needs to be trimmed, how do I know to call string_trim or array_trim unless I inspect each object before I call the appropriate trim function? The fact that functions are first-class in JavaScript means that each object in the array can carry its appropriate trim function with it. Is writing “obj.trim(obj)” OOP or functional programming?

    You may be interested in some of the work Oliver Steele has done on functional programming in JavaScript

    http://osteele.com/archives/2007/07/functional-javascript

    Comment by Peter Michaux — June 29, 2008 @ 12:40 pm

  3. I think that functional programming would be a tiny bit faster. Assuming there are many static functions that you attach to an objects prototype, it should take longer for JavaScript to actually find the prototyped function. First it will look through the objects functions, than go up the prototype chain. Whereas functional programming will be a direct pointer to the desired functionality.

    I did a quick time analysis, because I’m interested to see which one was faster. I attached a trim method to the prototype of a string, created a STRING_TRIM function, and added a trim function directly to a string object. If the string was an object, all functions ran about the same amount of time, the time difference was pretty much negligible (about 2 or 3 milliseconds difference after running each function 10,000 times). If the function was a literal, I could no longer run the trim directly attached to the string (which is to be expected). So the difference was in a prototyped string method or the STRING_TRIM method. The difference was about 50ms, the STRING_TRIM running 4/5 faster. Still, a rather small number considering there were 10,000 iteratations.

    I would still probably go the OOP route. It leads to more succinct, clearer code.

    Comment by MillsJROSS — June 30, 2008 @ 6:02 am

  4. Thanks for the great comments.

    Michael, that is a big problem. My policy to write functions that do not change the original object when dealing with JavaScript primitives. However, I don’t have a good convention yet when using the module pattern.

    MillJRoss, great analysis. I had similar expectations. There are few operations that are run 10,000 times on a page, but if every method was sped up by a few milliseconds, then I believe we would see a noticeable, page-wide performance improvement.

    Comment by Matt Snider — June 30, 2008 @ 9:54 am

  5. Lon, good point. PHP isn’t a functional programming language. As you stated, Functions are not first order objects in PHP. I should have written ‘function-driven’ or something like that. I have corrected my post.

    Comment by Matt Snider — June 30, 2008 @ 1:46 pm

  6. I’m not so sure it would be worth the effort. My time analysis wasn’t by any means deep, and it doesn’t take into consideration any time complexities that might arise from clogging the namespace with a bunch of utility functions. Also, the time analysis was done using only one browser and browser version.

    If I wanted to develop a bunch of utility functions, I’d probably just append them to an object, like util.STRING_TRIM. The trim function is a bit confusing attached to the String object, because it doesn’t change the object itself (this could be fixed by renaming the function get_trimmed), whereas a utility function implies that you’re not changing the object but returning a value(This, by the way, is extremely picky, as trim is so common that it’s intention should be understood easily). The other advantage to the utility function is that it is easier to read, in that the verb is before the noun, which is more natural in English.

    Comment by MillsJROSS — July 1, 2008 @ 6:38 am

  7. Q: “Are there Frameworks written for Functional JavaScript?”
    A: MochiKit! http://mochikit.com

    Functional and OOP style *complement* each other, you don’t need to choose - use both.

    Comment by Fredrik — July 7, 2008 @ 3:42 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress