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 instead of the function declaration. 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.

Here’s a typical example of a named function:

  1. function flyToTheMoon()
  2. {
  3.   alert("Zoom! Zoom! Zoom!");
  4. }
  5. flyToTheMoon();

Here’s the same example created as an anonymous function:

  1. var flyToTheMoon = function()
  2. {
  3.   alert("Zoom! Zoom! Zoom!");
  4. }
  5. flyToTheMoon();

Anonymous functions are created using the function operator

The two most common ways to create a function in javascript are by using the function declaration or function operator. Anonymous functions are created using the function operator.

If the function keyword appears first in the statement and is followed by a function name, the function is being created by a function declaration:

If the function keyword appears anywhere else, it is probably being used as a function operator:

When the function operator is called, it creates a new function object and returns it. Here’s an example that creates a function and assigns it to a variable called flyToTheMoon:

  1. var flyToTheMoon = function() {
  2.   alert("Zoom! Zoom! Zoom!");
  3. }

The assignment works in exactly the same way you’d assign the return value of any function to a variable, the only special thing is that the value is a function object rather than something simple like a number or a date.

This is possible because functions in javascript are just a special type of object. This means they can be used in the same way as any other object. They can be stored in variables, passed to other functions as parameters or returned from a function using the return statement. Functions are always objects, no matter how they are created.

Once the function has been saved to the variable, the variable can be used to invoke it:

  1. flyToTheMoon();

Anonymous functions are created at runtime

The function operator can be used anywhere that it’s valid to use an expression. For example you can use the function operator when a variable is being assigned, when a parameter is being passed to a function or in a return statement. This is possible because the function operator is always invoked at runtime.

Function declarations are different. They are run before any of the other code is executed so the functions do not have to be declared before the code that calls them.

Function declarations can’t be used to create anonymous functions because they require the function to have a name. The function declaration uses the function name to add it as a variable in the current scope.

Anonymous functions don’t have a name

This seems a little strange because how would you invoke a function that has no name? It works because the function name is something different to the variable that holds the function object.

Functions created with a function declaration always have a function name and a function variable that are exactly the same because the function declaration automatically creates the variable for you:

  1. function flyToTheMoon() {
  2.   alert("Zoom! Zoom! Zoom!");
  3. }
  4. flyToTheMoon();

For functions created with the function operator, the name is optional. In most cases, the name isn’t important to us so we create an anonymous function that has no name like this one:

  1. var flyToTheMoon = function() {
  2.    alert("Zoom! Zoom! Zoom");
  3. }
  4. flyToTheMoon();

However, the function operator does support setting a name if you want. Here is the same function again, only this time with a function name:

  1. var flyToTheMoon = function flyToTheMoon() {
  2.    alert("Zoom! Zoom! Zoom");
  3. }
  4. flyToTheMoon();

Giving your function a name does not automatically add a variable into scope with the function name. You still need to assign the return value of the function operator a variable.

In the previous example, the variable that stores the function object and the function’s name are the same, but they don’t have to be:

  1. var thingsToDoToday = function flyToTheMoon() {
  2.    alert("Zoom! Zoom! Zoom");
  3. }
  4. thingsToDoToday();

Why have a name?

The function’s name can be used to call the function from inside the function itself. That can be useful for recursive functions.

  1. var thingsToDoToday = function flyToTheMoon() {
  2.   if(!onTheMoon)
  3.     flyToTheMoon();
  4.   else
  5.     alert("One small step for a man..");
  6. }
  7. thingsToDoToday();

It can also useful for debugging because you can see the function’s name in a call stack. Anonymous functions generally all look the same in the call stack. If you have a nasty debugging situation, sometimes giving names to the functions you are interested in can make things clearer.

Why are anonymous functions useful?

Not having to set a name for an anonymous function is just a convenience thing since in most cases the name of the function doesn’t really matter. Most of the time anonymous functions and named functions will both do any job perfectly well.

Functions created with the function operator can be very useful. See some examples of where it can be used.

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.

Posted on 23 Aug 08 by Helen Emerson (last updated on 07 Apr 13).
Filed under Javascript

Comments

ledaker 07 Oct 2008

now, i am seeing clearly in jquery jungle, thankx for all

sam 28 Oct 2008

it’s very clear. thanks

Mike 13 Feb 2009

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.

Marc Knaup 27 Feb 2009

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.

ted devito 11 Mar 2009

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”

Helen 12 Mar 2009

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.

Helen 11 Apr 2009

@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).

Ralph 23 May 2009

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.)

Helen 24 May 2009

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. :)

Ralph 24 May 2009

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.

anon 25 Oct 2009

Your semi-colons are in the wrong place in your first eatcake example.

helen 01 Nov 2009

Thanks for letting me know! I don’t know what happened there. I’ve fixed it up now. :)

Jim 21 Feb 2010

This is a great post!! Examples are excellent and written very well! Keep the articles coming!

Andrey Marushkevych 07 Mar 2011

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”.

Anish 06 Apr 2011

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!!

Til 08 Jun 2011

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.

Anon 12 Jul 2011

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);
})();

Steve 04 Aug 2011

Just fyi, I can’t access anonymous5.html

Dude 29 Sep 2011

Very nicely explained, thanks!

Do you have any advice for accessing an event from an anonymous function?

Adrian 04 Nov 2011

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.

Derek 18 Nov 2011

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.

Casey 02 Jan 2012

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.

Helen Emerson 02 Jan 2012

Thanks for the suggestion. Will do.

Yogi 18 Jan 2012

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

Johan 30 Jan 2012

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!

Helen Emerson 12 Feb 2012

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

Sk 16 Feb 2012

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?

Helen Emerson 18 Feb 2012

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?

Sk 21 Feb 2012

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.

ujjaini 30 Mar 2012

very useful, very well written and lucid
thanks !

fluffy 06 Apr 2012

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.

Michael 09 May 2012

Thank you !

Raith 17 May 2012

When describing the function statement vs. function operator (first example on the page) you could point out that function statements are inserted into the relevant scope at parse-time (refer to “hoisting”) whereas operators are evaluated during run-time. Using function operators makes the execution order more critical, but also more logical IMO.

alert(typeof myFuncStatement); // “function”

function myFuncStatement () {
// this function is available to use immediately after parsing, even if the code containing this function statement is never reached!
}

// compare to

alert(typeof myFuncOperator); // “undefined”

var myFuncOperator = function () {
// this function is only available to use from now on!
}

alert(typeof myFuncOperator); // “function”

Olivier 30 May 2012

very clear article (well, until the dynamic programming example which is, IMO, too complex to hold the “quick-info-searching” reader attention ;). Anyway, thanks.

In the first code example, I noticed a semicolon after the “regular” function declaration? If I’m right, no need here. Precisely that semicolon makes distinction between regular function use and anonymous function use, since the later is on-the-fly declaration and run, so eventually a statement (as shown in the second code example).

Sorry for my english, did my best :D

Trackbacks