Home > JavaScript > First-class functions in JavaScript

First-class functions in JavaScript

In JavaScript functions are first class objects. JavaScript isn’t alone in this by any means, but it’s a very powerful feature that a lot of beginners are unaware of.

To start off, think of a variable declaration:

var room_number = 1406;

and you can pass that into any function, like so:

alert(room_number);

Well you can do the same thing with functions. Basically there are two common ways to create functions, and another less common way. Everybody reading this is probably familiar with this form:

function say_name(name) {
    alert('Your name is ' + name);
}

Obviously we’ve created a function called ‘say_name’ and if I want to use it, simply call say_name("Jon"). However we can accomplish the same thing with the following:

var say_name = function(name) {
    alert('Your name is ' + name);
}

In this case we created an anonymous function and then gave it a name. Another nice feature here is that we can do the same thing when adding an event handler — just pass the anonymous function. Look at the two snippets below:

function announce_click(event) {
    alert("you clicked!");
}

var myButton = document.getElementById("myButton");
myButton.addEventListener("click",announce_click,false);

Passing the function name to addEventListener, and…

var myButton = document.getElementById("myButton");
myButton.addEventListener("click",
                               function (event) {
                                     alert("you clicked!");
                               },
                               false);

…passing an anonymous function to do the same thing.

A word of caution though. When using removeEventListener, you must pass it the same function. Another anonymous function that does the same thing is not good enough. So if you never need to remove an event handler then declaring the function in the handler works great. Otherwise, it’s often a good idea to give the function a name so you can refer to it later.

Well, that’s all fine and dandy, but what else can you do with it? Well, it’s a natural fit for a callback. For those not familiar with the term callback, it’s simply a way of telling the function you’re calling to call another function as well. In the examples above, addEventListener took a callback in the 2nd parameter.

If you’re familiar with PHP’s callback system of passing a string with the name of the callback, rest easy. This is much better. JavaScript 1.6 has a map function on Arrays, but since backwards compatibility is often critical, I could use something like the following:

function map(callback,array) {
    var ret_array = [];
    for(var index = 0, length = array.length; index < length; ++index) {
        ret_array[index] = callback(array[index]);
    }
    return ret_array;
}

The map function will loop through the elements of the array and, for each one, call the function callback and pass it the value of the element. Then it assigns the value returned by callback to the matching index in a new array. Finally, it returns the new array.

The important thing here is that callback could be just about anything. Consider this:

function square(number) {
    return number * number;
}

var my_array = [1,2,3,4];

var squared_array = map(square, my_array);
//squared_array contains [1,4,9,16]

As you can see, using the map function we were able to easily apply the same function to every element of the array and get an array of the return values. Obviously the possible applications are pretty much endless. Have fun with it. Just remember that functions are objects too -- which brings me to the third, much less common way of creating functions. I can't say as I've ever seen this in the wild, and I don't recommend using it, but for completeness here it is:

var say_name = new Function("name", "alert('Your name is ' + name);");

Comments:2

Leave a Reply
  1. Reply Colin
    11/06/19

    Hi,
    Thanks for your posts: I’ve really enjoyed reading them.

    As for event listeners, I think it’s bad how if you set an anonymous function, it can’t be removed using removerEventListeners. The idea of creating an unstoppable event listener is just silly!

    Hopefully this problem will be solved in the future:
    http://www.w3.org/TR/2002/WD-DOM-Level-3-Events-20020208/changes.html
    I’ve no idea how long it would take for “eventListenerList” to be implemented in browsers though…

  2. Reply Colin
    11/06/19

    Okey, it appears that the url I linked to was old and the implementation of “eventListenerList” is no longer planned :(

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackbacks:0

Listed below are links to weblogs that reference
First-class functions in JavaScript from Ashita.org
TOP