There are three main technologies that your browser employs to present HTML for you: XSL, CSS and Javascript. The first two of these are functional: that is, they turn your incoming (X)HTML documents into a set of functions, or behaviours if you like. Because CSS isn’t generally considered a language, let alone a functional one, then it’s worth seeing an example in both languages. Here’s the CSS:
p.intro { color: green; }
And here’s a sort-of XSL equivalent:
<xsl:template match="p[@class='intro']">
<p color="green"><xsl:apply-templates /></p>
</xsl:template>
They both take place in the context of some generic processor, which rattles through the document executing default rules (XSL: strip out all but text nodes; CSS: apply the plain styles of your browser) unless your program—a list of disconnected rules, really—tells it differently. The combination of (XSL/CSS)+(X)HTML+defaults is thus turned into an explicit script for the browser to run.
So far, so reasonable. But what about the third technology, Javascript? Well, plain Javascript is an object-oriented procedural language. It orders the browser around for a bit, and then when you want to do something to the current page, Javascript manipulates the (X)HTML tree by grasping hold of it with both hands and giving it a tug, using DOM methods like .getElementById(id)
and attributes like .parentNode
. This procedural approach expects the tree to have a certain structure, or at the very least has to keep checking if the structure has changed and coping with that. This means that the programmer generally has to construct a lot of loops over, say, child elements, and also check for existence a lot. There’s a slight anomaly, in that you could think of the event-driven aspect of Javascript as being functional—it turns the user’s input through clicks, mouse movement and keypresses into browser behaviour, remaining otherwise dormant—but by and large Javascript’s meat is procedural.
There’s two routes you can take at this point. You can either say that, because Javascript is meant to be object-oriented, then the best way to work with it is to augment its functionality and simplify object construction, but ultimately leave it as that: if it weren’t functional, then it wouldn’t be Javascript. Or you can say that, given the advantages that XSL and CSS gain by being functional—a kind of “safety”, some scaleability, and document-driven processing—Javascript might want to have a piece of that too, while sacrificing some of its object orientation.
The first route is entirely laudable, because some problems are object-shaped and some are function-shaped. But, in the spirit of adventure, let’s investigate the second route for a while: pack some sandwiches and get some stout shoes on, and I’ll meet you in my next blog post.