Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Introducing Functions

Anonymous functions

I don't understand these, and even what is different with how they are written

2 Answers

Hi Nick

an Anonymous function works the same as a named function with 2 key differences.

  1. An anonymous function is dynamically declared at runtime.
  2. because the function is run at runtime it does not need a name, therefore an anonymous function does not have a name

The examples given from the video:

This is a named function, as you can see the function has a name and to use this function, we must call it.

// A named function
function myFunction() {
  // do a bunch of stuff here
}

myFunction();

An Anonymous function on the other hand does not have a name and does not need to be called, the function is dynamically declared at runtime and stored in a variable.

// Anonymous function
var myFunction =  function () {
  // do stuff here
};

Why the difference?

They both are useful and either may work better in more complex situations but for now it comes down to convenience and cleaner code. A named function and anonymous function can do the same thing, its your own personal opinion as to whether you use one or the other for different situations

You will soon notice when one is better than the other, like which one is more useful in an if statement for example.

An Anonymous function is a function without a name. They are less portable than named functions ( as in they can't be referenced on their own elsewhere in the code without being assigned to a variable). The alternative is a named function, which can be written elsewhere in the code and referenced whenever you need it.

Anonymous functions are usually used in callbacks as code executed after an event has been fired.