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 trialSjoerd Vermeijden
5,840 PointsWhy would i want to use an anonymous function over a named function?
Why would i want to use an anonymous function over a named function? It seems like the named function would do the job just aswel
2 Answers
Steven Parker
231,248 PointsA named function would do the job as well, but sometimes you don't need a name.
For example, if you're passing a callback function and your coding the complete function in the argument of the other function you are passing it to. This is a very common practice seen in code all the time. It just doesn't need to have a name. And by not naming it, it cannot get accidentally overwritten later in the code.
darryn
17,367 PointsYouโll find that there are a lot of one-off anonymous functions written in JavaScript.
These functions are written to be used once (like our callback functions).
If you know the function isnโt going to be reused, naming it or storing it to a variable doesnโt make sense. It would just add unnecessary lines of code to your project.
Andrew alludes to this in the first lesson of Callbacks with Timers.