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 Foundations Functions Anonymous Functions

Culture Foundry
Culture Foundry
8,396 Points

The thing I don't get, is why would we ever use an anonymous function? Why not just name them all?

It seems that they only cause confusion in debugging, I'm not seeing the value of having them.

2 Answers

Hi Culture, see if the below explanation helps some.

What are anonymous functions for? Benefits?

Simply, anonymous functions are used for the reasons of: a) code brevity. It often makes sense to use anonymous functions calls in callbacks and event handlers; b) scope management. Anonymous functions can be used to create temporary/private scope; c) Anonymous function are often handy in closures and recursions.

In JavaScript, scope could be tricky but it is fundamental to JavaScript understanding. And anonymous functions are often used to create a temporary / private scope.

A commonly cited example is jQuery. —JavaScript: Anonymous functions

Culture Foundry
Culture Foundry
8,396 Points

Thanks! This clears up a lot.

Daniël van der Winden
Daniël van der Winden
3,716 Points

I had the exact same question. Thanks for clearing that up, Dustin.

Makes perfect sense. Thanks Dustin!

Culture Foundry, you're right about the debugging problem with anonymous functions. You might want to read Kyle Simpson's take on Anonymous vs Named from his book series "You Don't Know JS".