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

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() {
     $(this).prev().show();
     $(this).remove();
});

Thanks

3 Answers

It is less typing to just do

$('button').click(function(){
     $(this).prev().show();
     $(this).remove();
});

The idiomatic way to use named functions is to do:

function doSomething(thing){
  return thing + 1
}

doSomething(3);

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
STAFF
Dave McFarland
Treehouse Teacher

Chris Feltus

You can also write it this way:

function doSomething() {
  $(this).prev().show();
  $(this).remove();
};
$('button').click(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..