Coding with Jesse

JavaScript Functions are Variables

December 29th, 2007

JavaScript functions are variables, and this is a big difference between JavaScript and many other programming languages. It can be a bit of a paradigm shift for people new to JavaScript, but it allows for some really cool things you can't do in many other languages.

When I say functions are variables, I mean that they're treated much the same as arrays, numbers, strings and objects. That means you can do some neat things.

You can define and redefine functions as local variables:

var myFunc;

if (Math.random() < 0.5) {
    myFunc = function() {
        alert('heads');
    };
} else {
    myFunc = function() {
        alert('tails');
    };
}

myFunc(); // alerts "heads" or "tails" depending on random value

You can also pass functions as parameters to other functions, which is very useful for callback functions:

function do_something(callback_function) {
    alert('hello');

    if (callback_function) {
        callback_function();
    }
}

var my_callback = function() {
    alert('goodbye');
};

do_something(my_callback); // alerts "hello" and then "goodbye"

You can also return a function from a function:

function get_multiplier(factor) {
    return function(num) {
        return num * factor;
    };
}

var times_5 = get_multiplier(5);
var result = times_5(10);

alert(result); // alerts "50"

var six_times_two = get_multiplier(6)(2);

alert(six_times_two); // alerts "12"

You can also define "anonymous" functions without a name and even execute them:

(function(first_name, get_last_name) {
    var last_name = get_last_name();

    alert(first_name + ' ' + last_name); // alerts "Jesse Skinner";
})('Jesse', function(){ return 'Skinner'; });

Note that in order to execute an anonymous function you have to wrap it in () parentheses first.

So that's just some of the unusual stuff you can do with JavaScript. Once you get familiar with the concept, you can really start to reuse code in great new ways.


Interested in web development? Subscribe to my newsletter!

Comments

1 . nitinpai at 2008-01-03T06:22:45.000Z

nitinpai

Hey Jesse,

Aren't such functions referred to as closures?

2 . Jesse Skinner at 2008-01-03T11:42:54.000Z

Jesse Skinner

Sure, functions can be closures if they're used to create a new scope that anchors down some variables. But I think the word closure is referring to this effect alone - surely you can do lots of other cool stuff with functions :)

3 . Veeresh at 2008-05-10T03:56:04.000Z

Veeresh

Informative article, it helps allot for a static content for dynamic access.

Thanks,

Veeresh D.
http://drveresh.googlepages.com

4 . andris at 2008-10-22T23:35:25.000Z

andris

if (callback_function) {
callback_function();
}

I better it replace with
if( typeof callback_function == 'function' ) callback_function();

5 . Oscar at 2009-01-23T23:59:49.000Z

Oscar

Nice and useful!

6 . Vijay Karla at 2009-04-11T12:04:22.000Z

Vijay Karla

Nice article
Is it possible to call a fuction doSomething with one of its parameter the the fuction poiter, and then execute the function pointed by the variable inside doSomething?

7 . Jesse Skinner at 2009-04-12T17:54:33.000Z

Jesse Skinner

@Vijay - sure, that's basically what's happening in the 2nd example above.

8 . Zach at 2011-02-16T05:57:15.000Z

Zach

Thanks for the post! Quite helpful because I was wondering why some examples were using functions like within variables instead of just regular functions.

9 . Gavin Kistner at 2011-04-22T15:57:36.000Z

Gavin Kistner

The title of this entry and the terminology it uses are incorrect and confusing (at best) and misleading. Variables are not values, and values are not variables. A function is not a variable any more than an array is a variable. They may be referenced by variables.

10 . jP at 2011-06-04T18:39:56.000Z

jP

Thanks for this post. It was exactly what I've been wanting to know.

11 . Hug0 at 2011-09-29T09:33:31.000Z

Hug0

Gavin Kistner: Agree, glad that someone has pointed it out.