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!

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


Naming Jquery Functions

I have been working with anonymous functions up until now, and would like to use some named functions. Below is an anonymous function and it works just fine

The code for a named function below appears to work, but I just wanted to verify I am doing this correctly.

$('button').click(function doSomething() {


3 Answers

It is less typing to just do


The idiomatic way to use named functions is to do:

function doSomething(thing){
  return thing + 1


A lot of times in javascript you never use the name of the function because it's in a callback. (Like your example), you only need to name a function if you're going to explicitly call it by name.

Dave McFarland
Dave McFarland
Treehouse Teacher

Chris Feltus

You can also write it this way:

function doSomething() {

The named function goes outside of the event handler. In addition, you pass just the name of the function -- doSomething -- to the .click() method. Don't add parentheses to doSomething in the click method. This, for example is wrong: $('button').click(doSomething());

However passing anonymous functions is the more common way to do it.

it make sense to used named function if you use some functionality in different places..