Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Callback Functions in JavaScript Callbacks with Timers Using Anonymous Functions with setInterval

Why 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
Steven Parker
216,012 Points

A 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
darryn
17,355 Points

You’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.