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 trialCulture Foundry
8,396 PointsThe 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
Dustin Matlock
33,856 PointsHi 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
wuworkshop
3,429 PointsCulture 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".
Culture Foundry
8,396 PointsCulture Foundry
8,396 PointsThanks! This clears up a lot.
Daniël van der Winden
3,716 PointsDaniël van der Winden
3,716 PointsI had the exact same question. Thanks for clearing that up, Dustin.
Zach Allan
19,452 PointsZach Allan
19,452 PointsMakes perfect sense. Thanks Dustin!