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 trialBen Flores
17,074 PointsWhy are we able to create a named function and then call it without parenthesis?
I understand we created passwordEvent() to keep our code dry. I don't get, however, why down below when we call it inside focus we do so like this:
$("#password").focus(passwordEvent);
Is this because .focus() takes a function inside, so we don't need to use the parenthesis? Otherwise to call that function they would be necessary, correct?
3 Answers
Jason Anders
Treehouse Moderator 145,860 PointsHey Benjamin,
In JavaScript, functions are "first-class citizens" and can be used as parameters for other functions
With that in mind, you are correct that when you call a function, it needs the (). However, in the example you have provided, you are simply passing in the function as a parameter
into the focus()
function.
Now when you call the focus
function, you will need to pass in the parameters needed for the passWordEvent
function.
If you're still unsure, have a look at the MDN documentation.
Keep Coding!
Jakub Łątkiewicz
5,181 PointsYou use parenthesis if you want to call the function. You use the function name if you want to reference it.
Adrien Contee
4,875 PointsMan I had this same problem in the beginning... I couldn't wrap my head around it. All this Higher Order Functions, and First Class Functions business didn't help either. The best way I can tell you is the way I understood it.
You know you can declare functions in a couple of ways.... anonymous, as a declaration, and as expressions. Since anonymous isn't relevant here I'll leave that aside.
When declaring a named function you can either include the name in the function declaration itself or as the variable name in an expression.
A Function Declaration:
function myFunc() {
//block of code
}
can also be written like this:
var myFunc = function() {
//block of code
}
So when you are passing the function myFunc to another function... you are not calling it... you are passing a reference to it.
Hope this helps!