Javascript anonymous functions
Anonymous functions are functions that are dynamically declared at runtime that don’t have to be given a name.
Anonymous functions are declared using the function operator. You can use the function operator to create a new function wherever it’s valid to put an expression. For example you could declare a new function as a parameter to a function call or to assign a property of another object.
The function operator returns a reference to the function that was just created. The function can then be assigned to a variable, passed as a parameter or returned from another function. This is possible because functions are first class objects in javascript.
Here’s an example where a function is declared in the regular way using the function statement:
-
function eatCake(){
-
alert("So delicious and moist");
-
};
-
eatCake();
Here’s an example where the same function is declared dynamically using the function operator:
-
var eatCakeAnon = function(){
-
alert("So delicious and moist");
-
};
-
eatCakeAnon();
Why is this useful?
Anonymous functions are a really useful part of javascript. Once you understand what they are, you’ll start seeing them everywhere in javascript code examples and libraries.
Pass logic to another function
Anonymous functions are also really handy when you need to pass a little bit of code to a another function. If the function you need is very short, it’s often convenient to declare it when you call the function you want to pass it to:
-
window.addEventListener("load",
-
function() { alert("All done");},
-
false);
Declaring single use functions
Anonymous functions can help make code more concise when declaring a function that will only be used in one place. Rather than having to declare the function and then use it you can do both in one step. It’s particularly useful for things like declaring event handlers and assigning methods to objects.
For example, if we’re creating a constructor function, we’ll need to declare the object’s methods and then assign them to the object’s properties so they can be called outside the object. It’s possible to declare the function and then assign it to a variable as a separate step like this:
-
function Pet(name, species, hello){
-
this.name = name;
-
this.species = species;
-
this.hello = hello;
-
function sayHello()
-
{
-
alert(this.hello);
-
}
-
this.sayHello = sayHello;
-
}
But it’s a bit more convenient and concise to do it all as one step:
-
function Pet2(name, species, hello){
-
this.name = name;
-
this.species = species;
-
this.hello = hello;
-
this.sayHello = function()
-
{
-
alert(this.hello);
-
}
-
}
Both syntaxes have exactly the same result. The anonymous function just keeps the function declaration in the place where it will be used and saves a few lines of code.
Declaring a function without adding a variable to the scope
Anonymous functions don’t automatically get a name so they won’t potentially overwrite other variables in the current scope.
If you’re working in the scope of another function, this isn’t such a big deal. You can (hopefully) keep track of all the variables in scope in your head. It’s can just be a convenience not to have think of a name for a function that you are going to straight away assign to another value and will never want to call by name. It’s just neat programming. In the example above, we don’t really get any benefit from giving the sayHello function a name in the local scope.
If you’re working in the global scope (and you really shouldn’t be if you can help it) it becomes critical because the global scope is a lot bigger and it can be a lot harder to see what’s declared already. Javascript won’t tell you if you declare a variable twice. It will just overwrite the original with the new one. This is even more likely if you start using javascript from multiple sources like third party javascript libraries.
Namespacing in javascript works in exactly this way. It uses objects literals and anonymous functions to give each function a scope so the global scope doesn’t end up full of potentially conflicting names:
-
var helephant = {
-
bakeCake : function()
-
{
-
alert("flour + eggs + sugar");
-
},
-
eatCake : function()
-
{
-
alert("So delicious and moist!");
-
}
-
}
-
helephant.bakeCake();
-
helephant.eatCake();
Provides scope for variables
Variables are scoped at the function level in javascript. This is different to what you might be used to in a language like C# or Java where the variables are scoped to the block. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.
If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:
-
(function() {
-
var myProperty = "hello world";
-
alert(myProperty);
-
})();
-
alert(typeof(myProperty)); // undefined
Some people use this if they want to do some processing the global scope but don’t want to add new members.
Dynamic programming
One of the big differences between javascript and more traditional languages like C# is that javascript is dynamic. Anonymous functions is one of the big ways to take advantage of that in your code.
Imagine that you’re an programmer who has created a new type of textbox that filters the user’s input based on data type. So you can say that the user is only allowed to enter numbers into the textbox and any other characters will be filtered. You’re using the ASP.NET ajax framework (because the place you work is a Microsoft shop and you have to) and the convention for ASP.NET ajax server controls is to use a get/set method to access any properties on your object.
Your textbox has three different properties (maxLength, cssClass and dataType) which means six boring little methods you have to write that will just clutter up your textbox’s javascript declaration and won’t really add anything to the logic.
Here’s a bit of a subversive idea.. why don’t we get the computer to do the work? Why don’t we make the textbox automatically generate the get/set methods from the properties when it initializes itself? That way we can have six less methods in our javascript object and if we add another property it will automatically get the methods.
This example creates an init function that takes a list of server properties and values and then creates a getter and setter on the object for each one. This is possible because we can create as many new anonymous functions as we like at runtime:
-
$helephant.components = {
-
init : function(object, serverProperties)
-
{
-
for(var property in serverProperties)
-
{
-
// set the textbox's property
-
$helephant.components.createGetter(textbox, property);
-
$helephant.components.createSetter(textbox, property, serverProperties[property]);
-
}
-
},
-
-
createGetter : function(object, property)
-
{
-
var propertyName = "get_" + property;
-
if(typeof(object.constructor.prototype[propertyName]) == "undefined")
-
{
-
object.constructor.prototype[propertyName] = function()
-
{
-
return this[property];
-
};
-
}
-
},
-
-
createSetter : function(object, property, initialValue)
-
{
-
var propertyName = "set_" + property;
-
if(typeof(object.constructor.prototype[propertyName]) == "undefined")
-
{
-
object.constructor.prototype[propertyName] = function(value)
-
{
-
this[property] = value;
-
};
-
}
-
if(typeof(initialValue) != "undefined")
-
object[propertyName](initialValue);
-
}
-
}
The code that calls the methods never needs to know they were dynamically generated. It calls them in exactly the same way as a usual method:
-
var maxLength = textbox.get_maxLength();
-
textbox.set_cssClass("redAlert");
Another example of this is in the JQuery library where they set up the convenient helper methods for binding to events from a list of events that are supported:
-
jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
-
"mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
-
"submit,keydown,keypress,keyup,error").split(","), function(i, name){
-
-
// Handle event binding
-
jQuery.fn[name] = function(fn){
-
return fn ? this.bind(name, fn) : this.trigger(name);
-
};
-
});
This may look a little unfamiliar to people who are used to statically typed languages like C#. What you have to remember is that you don’t get the static typed safety in javascript whatever you do because javascript doesn’t work like that. The only thing you can do is try to get the most out of the language features that javascript does have.
What’s next?
Sometimes you want to create a lot of objects with the same properties and methods. Constructor functions are you very own object factories that can stamp out as many objects with the same type as you need.
This article is part of a set of related posts about How javascript objects work.

October 7th, 2008 at 5:54 am
now, i am seeing clearly in jquery jungle, thankx for all
October 28th, 2008 at 8:08 am
it’s very clear. thanks
February 13th, 2009 at 10:36 pm
You put a lot of work into that tutorial, and I got a lot out of it. I’ve been programming javascript since the late 1990’s, yet scope and closures are still somewhat of a weird science to me.
February 27th, 2009 at 11:58 am
The first example of ‘Dynamic programming’ does not work – Chrome, Firefox and Internet Explorer always access the dataType property. Using outer iterator variables in functions does not seem to work.
March 11th, 2009 at 12:48 pm
so just doing some tests in firebug here, it looks like if function names are not protected.
//so this function…
function addFive (n) { return n+5; }
// can be redefined as a string
addFive = ’something else’;
// and you would have no trace of the original
alert(addFive(3)); // “TypeError: addFive is not a function”
March 12th, 2009 at 5:37 pm
That’s right. They’re just a variable so you can overwrite the variable with something else. Javascript isn’t strongly typed so the new value doesn’t even have to be the same type as the old one.
There’s a nice tool called JSLint that you can run over your code that will warn you if you try to do things like that. There’s two versions, one from Douglas Crockford (http://www.jslint.com/) that’s very strict and one that’s built on top of mozilla’s javascript engine (http://www.javascriptlint.com/) that you can run from the command line (or visual studio if you use it). In both you can configure what rules you want it to check for.
April 11th, 2009 at 6:36 am
@Marc yes, you’re right. :) That code example makes a classic mistake with closures and loops. The closure will only be created for the last value of the loop, so every time the inner function gets called (the get_something or set_something function), the property value will be set to the last property value in the loop.
I actually talk about this in my article on closures (http://helephant.com/2008/10/javascript-closures/) so it’s a little embarrassing to find the same mistake in one of my earlier examples. :)
The way to fix it is to create an inner function that will create a new closure for each different value in the loop.
I’ve fixed up the example in the article so it works now (sorry it’s taken me so long – life here has been crazy lately).
May 23rd, 2009 at 9:46 pm
Excellent post! Subversively clear! Thank you, Helen.
During many years of reading about Lisp through a glass darkly, at some point I noticed that an “anonymous function” might instead be called a “function literal.” Just as we have numeric variables such as
var mynumber;
so also we have numeric literals, for example, 123.45. The advantage of a numeric literal is that, instead of naming a number before using it, like this:
var more = 123.45; // named number
much = enough + more;
we can write, instead:
much = enough + 123.45; // literal or “anonymous” number
Very concise! Likewise we can use a string variable:
msg = “Let this be a lesson”;
alert (msg);
or, more briefly, a string literal:
alert (”Let this be a lesson”);
This is all rather clear and obvious when it comes to numbers and strings. It is just the same idea for “lambda” or “anonymous” functions instead of named functions, except that the concept of literalness is maybe not quite as obvious for a function.
I am convinced that the term “function literal” is more sensible, and comprehensible, than “lambda expression.” After all, lambda is only a modest Greek letter. We English speakers could be calling these things, say, “z expressions,” which doesn’t sound quite so mysterious. Then we wouldn’t even have to write “lambda,” because “z” is right there on the keyboard, unless you actually prefer “zee.”
Then again, in Lisp we are also supposed to talk about “s-expressions”…
Hmmm. I’m starting to see a pattern here! Maybe those original beardy Lisp guys at MIT were shy about using, you know, whole words?
(Full disclosure: I look embarrassingly similar to those original, beardy MIT guys. Sigh.)
May 24th, 2009 at 5:40 am
That makes a lot of sense. In javascript they even have the same concept for objects as object literals. It’s such a pity they made anonymous functions into such a big scary concept when really it’s actually pretty simple when you get your head around the ideas that functions can be stored as variables. :)
May 24th, 2009 at 2:39 pm
After I wrote that first comment, I searched for “function literals,” and found that the term is already used in connection with Javascript. As far as I can tell, in that context, a “function literal” is an instance of a lambda expression. But now it occurs to me that providing a function literal capability does not, by itself, allow a program to construct a completely new function at runtime. So now I’m mixed up again on the terminology. Does Javascript have the full “lambda” capability, or not?
As you put it, “It’s such a pity they made anonymous functions into such a big scary concept.”
I agree. Yet there are genuine problems with translating this kind of algorithm-think into human thought. For example, I was just reading something about the “lambda calculus” (yuck, what a name) here:
http://en.wikipedia.org/wiki/Lambda_calculus
In that article, below the heading “Informal Description,” the following three lines are said to be equivalent:
I: (λ f. f 3) (λ x. x + 2)
II: (λ x. x + 2) 3
III: 3 + 2
When I finally forced myself to work through that derivation (yes, it is a derivation), I thought, Wow, that actually isn’t so easy!
My point is not just that lambda calculus is tricky — though it is tricky — but rather that the often-observed notational and descriptive problems with Lisp probably arise because it’s so difficult to describe such manipulations in English. Just try to write the above three lines in ordinary words! Here is my attempt, including pitiful references to nonexistent argument types.
I: “The function which applies its argument to 3, applied to the function which adds two to its argument”
II: “The function which adds two to its argument, applied to 3″
III: “3 plus 2″
While I don’t feel exactly stupid when I try to follow the above, I certainly don’t feel all beamed-up and glowing with intelligence, either. Here is one possible improvement, using a more familiar way of talking about functions, with the disadvantage that the order of writing is reversed:
I: “Feed (the function which adds two to its argument) to (the function which applies its argument to 3)”
II: “Feed 3 to (the function which adds two to its argument)”
III: “3 added to 2″
Suppose we try naming these hitherto-anonymous functions. Is the result any easier to understand?
DECLARATIONS:
1. plus_two = “the function which adds two to its argument”
2. apply_to_three = “the function which applies its argument to 3″
APPLICATIONS:
I: apply_to_three(plus_two)
II: plus_two(3)
III: 3 + 2
Now I see why it’s so difficult to describe what’s going on: the words get tangled up right away, even at that simple level. I guess that’s why Lisp winds up getting taught by example rather than by explanation, and why we are asked to use such peculiar words as “currying” and “closure,” words which seemed to drop on us from an unknown sky.
All this is very interesting, but is it useful? That question has been argued back and forth, using an infinite number of words, since the beginnings of Lisp.
There’s really no answer; nevertheless, it’s easy to observe that Lisp is hardly ever seen in a practical application. Some authorities would claim that’s only because the average programmer is stupid or ill-trained, and of course one is forced to consider that possibility, but after 50 years? By now the true brainiacs could have populated their own small country, with no mortals like us allowed, having three generations of pure functional thinkers! They would have been cranking out advanced-civilization software for decades, while we “normals” slowly returned to the life of our primate forebears, climbing up into the trees, taking it easy.
Yet nothing remotely similar has happened, despite valiant efforts. Nor did Lisp lead to huge new advances in “artificial intelligence” — sorry, that just didn’t work out.
Conclusion: I’m not rushing to switch to Lisp, or Ruby, but I still have high hopes for Javascript.
August 17th, 2009 at 10:29 am
[...] strengths as a dynamic language with features like first class functions, closures and anonymous functions to write concise and modular code rather than trying to make it act like a different type of [...]
September 2nd, 2009 at 1:01 am
[...] else in your code. We’ll discuss anonymous functions more in lecture two; You can also read this guide to anonymous functions in [...]
October 25th, 2009 at 11:59 pm
Your semi-colons are in the wrong place in your first eatcake example.
November 1st, 2009 at 7:32 pm
Thanks for letting me know! I don’t know what happened there. I’ve fixed it up now. :)
January 8th, 2010 at 10:34 pm
[...] How javascript objects workBuilding simple objectsFunctions are first class objects in javascriptJavascript anonymous functionsConstructor functionsJavascript closuresJavascript object prototypeJavascript prototype [...]
January 25th, 2010 at 1:03 pm
[...] we need to strip out the function name as when you assign a function to a variable it should be an anonymous function. To strip the name out we use the replace method [...]