Javascript anonymous functions
Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions.
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?
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 wiring up event handlers and creating methods in constructor functions.
For example, a constructor function will need to create methods for the object it is creating. It’s possible to declare the function using the function statement 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 more concise to use the function operator do it in one step:
-
function Pet2(name, species, hello){
-
this.name = name;
-
this.species = species;
-
this.hello = hello;
-
this.sayHello = function()
-
{
-
alert(this.hello);
-
}
-
}
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);
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.







Comments
now, i am seeing clearly in jquery jungle, thankx for all
it’s very clear. thanks
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.
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.
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”
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.
@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).
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.)
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. :)
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.
Your semi-colons are in the wrong place in your first eatcake example.
Thanks for letting me know! I don’t know what happened there. I’ve fixed it up now. :)
This is a great post!! Examples are excellent and written very well! Keep the articles coming!
Great explanation! Really enjoying your blog.
I think there is a typo in the $helephant.components.init() function – inside the for loop you are passing “textbox” instead of “object”.
Such a great article.
You’ve explained the concept of scope in relation to self-invoking functions so clearly.
The article is very simple and easy to read.
Thanks a lot Helen. You’re such a sweetheart!!
I found your explanation on anonymous functions very well said. I think you only need to add the fact that the format:
(function()
{
//code…
}
)();
also forces execution of whatever is inside. Thanks.
If you start a line with ( you should prefix it with ;
The below will throw an error since there is no ; before (function() {. Some programmers (like me) don’t use semicolons at line end.
var x=1
(function() {
var myProperty = “hello world”;
alert(myProperty);
})();
Just fyi, I can’t access anonymous5.html
Very nicely explained, thanks!
Do you have any advice for accessing an event from an anonymous function?
Though I like your clear layout very much, in the world of programming, your logic leaves a lot to be desired.
I quote:
“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.”
Really? So according to you, it’s useful because it’s useful and because we’ll start seeing them everywhere.
Then you move on to actually build on this nonsense with the word ‘also’ as if you previously gave a real reason.
“Anonymous functions are also really handy…”
I expect this from others, not from this realm, the realm that respects LOGIC.
The rest of your dissertation was actually useful but I had to get over my initial bad feeling about you. Not ideal.
I am working on a site with tons of anon functions. I am trying to debug where they are actually coming from. How can you do this? I am using all the firebug tools and extensions but it won’t say it what JS file or what function was called on it.
Your page here has some great explanations of anonymous functionality, but if you could get someone to review the actual English usage here, it would be even better.
Not trying to bust your balls or anything… It’s just that many errors are scattered throughout the page. If you could fix all this, your knowledge would reach many more people.
Thanks for the suggestion. Will do.
Hi
Thank you for this article.
I am unable to access this link – http://helephant.com/wp-content/uploads/2008/11/anonymous5.html
Please update if possible.
I liked the whole series of Java Script Articles on your site. Thanks once again for sharing wisdom.
Cheers
So, I get the point of using anonymous functions when:
- directly passing them as an argument to a function
- assigning them to a field of an object
- calling them directly (to reduce the scope of variables within the function body)
But in your first example with the eatCake() functions, is there any difference between how you may use eatCake and eatCakeAnon? (after they have been defined, that is)
Or is the function statement just a syntactic sugar, like in scheme?
Thanks for being a steady helping hand when entering the dynamic world of JavaScript!
I don’t think there’s any difference between whether they were created with the function statement (old style function declaration) or the function operator (to create an anonymous function). If there are differences, they are pretty subtle, not anything I’ve ever come across when writing javascript in a real project.
The big difference is where you can use the function statement vs where you can use the function operator.
Functions declared with the function statement are all evaluated before the javascript code is run so you can use it at the root of your script or within another function declaration, but not anywhere else. The big advantage of using the function declaration is you don’t have to declare the function before the code that uses it.
Functions created by the function operator are evaluated as the code is executed, which means it’s valid to use the function operator wherever it is valid to use any other type of javascript expression (to create parameters to functions, as a return from a function, inside an if statement..).
If you’d like to know more, I’d recommend having a read of this article: https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
I agree that anonymous functions are good and pretty handy. But what about when it comes to testing and test coverage. I use yui tests to do the testing . The only way to test these functions are to move them out under a namespace and then test them separately, but for me I think that creates a lot of function clutter under a specific namespace. Thoughts?
It’s a good question. How’s your javascript structured? Are you using javascript in a traditional OO way, more functionally or more procedurally? Is your javascript mostly UI focused (glueing bits of jquery or YUI components together) or does it also have some more abstract logic around it?
Yes, its mostly UI focused. We have JS specific to a components, each component talks to each other using events. Evert JS has its own namespace under which we have bunch of functions defined for specific actions. These can be tested easily, the problem arises when we have for Ex Event handlers to attach, where anonymous functions fit perfectly. For ex: Event.on(ele, ‘click’, function(){}, context);. This is where testing of these functions is a problem, especially if they have some logic involved inside , which more often than not is the case for me.
very useful, very well written and lucid
thanks !
Another very useful use of anonymous functions is to copy a value into a local scope. For example, a common JS error is to do something like:
for (var i = 0; i < 100; i++) {
someAsynchronousTask(function(result) { storage[i] = result; });
}
which is quite incorrect, as it'll be the value of 'i' when the task completes that determines what happens in the callback. The fix for this is:
for (var i = 0; i < 100; i++) {
(function(k){
someAsynchronousTask(function(result) { storage[k] = result; });
})(i);
}
Of course, if you're not using strict mode and don't care about the value of 'this' you can also do:
for (var i = 0; i < 100; i++) {
with ({k:i}) {
someAsynchronousTask(function(result) { storage[k] = result; });
}
}
but that tends to cause more problems than it's worth.
Thank you !
Trackbacks