Jimmy Breck-McKye

A lazy programmer

JavaScript Function Variables Don't Have to Be Anonymous

If you’ve used JavaScript much, you’ll probably know one of its very convenient features — the ability to assign functions to variables, send them as arguments, and return them as values. This lets you write code like this, where functions themselves return other functions:

Anonymous function bonanza
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
   This code creates a basic 'curry' function 
   (see my earlier post for an explanation)
   It relies heavily on function variables.
*/

var add = function(x, y) { // <- A function variable
    return x + y;
};

var curryUtil = {
    curry : function(functionToCurry, x) { // <- A function object property
        return function(y) {               // <- A function return value
            return functionToCurry(x,y);
        };
    }
};

var add7 = curryUtil.curry(add, 7);
add7(3); // returns 10

var double = curryUtil.curry(function(x,y){ // <- A function literal argument
   return x * y;
}, 2);
double(8); // returns 16

The problem with this, however, is that all the functions in the above example are anonymous — they aren’t named. Beyond making your code more obscure than it needs to be, this also makes debugging them a problem, because when you look at the browser’s call stack, you’re going to get something like this:

Yeah. Good luck with that.

However, you can remedy the issue quite easily &mdash because JavaScript lets you name your function variables:

Named function variables
1
2
3
4
5
6
7
8
9
var myFunction = function myFunction(x) {...}

var myObject = {
    myMethod : function myMethod(x) {...}
};

function returnSomeFunction() {
  return function myReturnedFunction() {...}
}

…name your function values…

Named function values
1
compose(function someComposedFunction(x) {...} )

…and name returned functions…

Named returned functions
1
2
3
function lambda() {
    return function returnedFunction(x) {...}
}

We can apply this syntax to our curry example. Let’s look again:

Named function variables in practice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
   Updated curry function
*/

var add = function add(x, y) {
    return x + y;
};

var curryUtil = {
    curry : function curry(functionToCurry, x) {
        return function curriedFunction(y) {
            return functionToCurry(x,y);
        };
    }
};

var add7 = curryUtil.curry(add, 7);
add7(3); // returns 10

var double = curryUtil.curry(function multiply(x,y){
   return x * y;
}, 2);
double(8); // returns 16

Because the function variables are named, they’ll now be much easier to debug:

Naming your function variables makes debugging much easier, takes little effort, and arguably can make for better readability too.

Comments