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 jQuery Basics (2014) Creating a Spoiler Revealer Perform: Part 3

Christopher campbell
Christopher campbell
1,996 Points

I'm sure this was already explained but what in the purpose of the empty function in JavaScript? And when to use it?

The best example of my question would be in line 9, "$("button").click(function(){". I'm kind of confused and would appreciate some help with wrapping my brain around this.

3 Answers

Justin Horner
STAFF
Justin Horner
Treehouse Guest Teacher

Hello Christopher,

The anonymous function you pass to the click function is what will be called when you click the button. In the example you've provided, it's simply a function with no arguments and that's why it has empty parenthesis. It's not actually an empty function because you defined the function block between curly braces.

I hope this helps.

Christopher campbell
Christopher campbell
1,996 Points

Thank you very much, I have much better understanding of anonymous functions and why it would be necessary in the example I provided.

Hey Christopher,

Anonymous functions are a great tool if you just need to use code in one place. For example, in that click method, the code within the function only needs to be executed in that particular spot, so he uses a blank function.

To decide whether you want to use a named function or an anonymous function, you should ask yourself, "Does this code need to be used anywhere else in my program?" If it does not, go with an anonymous function. If it does, go with a named function. Does that help some?

Ryan Field
PLUS
Ryan Field
Courses Plus Student 21,242 Points

Using an anonymous function here is just so you can say, "When X button is clicked, do Y", and write your script for that action inside that function. If you put an empty function there and leave it, it will do nothing when the element is clicked as nothing is included inside the function.

Were you perhaps confused about the difference between an empty function and an anonymous function?