Sunday, January 24, 2010

JavaScript by example: functions and function objects

I've been working in JavaScript a lot these last couple of months, and I feel like I've learned a lot. I wanted to show some of the more interesting aspects of JavaScript that I've had the opportunity to bump into. I'll use some simple examples along the way to illustrate my points.

Note: If you want to follow along with the examples in this blog post (and the followup posts), you'll probably want to use an interactive JavaScript environment. I tend to use Firebug with Firefox when I'm trying stuff out, but there shouldn't be anything in these examples that won't work in the WebKit console in Safari or Chrome, or in Rhino, for that matter.

Functions

A simple function is defined and used in JavaScript thusly:

function add(x, y) {
return x + y;
}
console.log(add(3, 5)); // this prints "8" to the console

This does just about what it looks like it does. There's no trickery here (the trickery comes later on). Let's say that we want a version of this function that takes a single argument, and always adds 5 to it. You could do that like this:

function add5(a) {
return add(a, 5);
}

console.log(add5(3)); // prints "8"

But what if you're going to need a bunch of these one-argument variants on the add function? Well, since functions are first-class objects in JavaScript, you can do this:

function make_adder(v) {
var f = function(x) {
return add(x, v);
};
return f;
}

var add7 = make_adder(7); //create a function
console.log(add7(3)); // prints "10"

This is only slightly more complicated than the original example. One possibly subtle point here is that the returned function "captures" the value of v that was passed into make_adder. In a more formal discussion, you'd call this a closure.