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 trialBappy Golder
13,449 PointsFunction call and parenthesis. Why aren't we using them here.
I thought we call/invoke a function with a parenthesis in he end like below:
myFunction();
However we are not using any parenthesis in the code below for the 'passwordEvent' function. Why is that?
//check to see if the password is valid
$("#password").focus(passwordEvent).keyup(passwordEvent);
2 Answers
Marcus Parsons
15,719 PointsHey Bappy,
You're right. When we call a function, we use () to denote to the compiler that we want the function executed right then and there. However, leaving off the () allows us to point to a function in the case of an event. The way the compiler works is that when () are beside of a function name, it will execute the function immediately. That would be a bad idea because the function would fire off immediately (without regard to the event handler) upon page load and then you wouldn't be able to use it further because there is no reference to it. If you leave off parenthesis, however, it will be used as a reference so that it can be called back. These functions are generally known as callback functions.
Jason Anello
Courses Plus Student 94,610 PointsHi Bappy,
It's because we don't want that function called at the point when this code is reached and executed.
Instead, we want to pass in a reference to the function so that the .focus
method can call our passwordEvent
function for us anytime the element receives focus.
If you put in the parentheses then that means the passwordEvent function will be called immediately when that code is reached and the return value of that function is what will be passed into the .focus()
method which is not the behavior we wanted.
Bappy Golder
13,449 PointsCheers Jason
audreysalerno
4,289 PointsThese are the kind of things that should be explained in the videos! There's a lot of explanations of HOW to get a desired result, but not enough of WHY things are being done the way they are.
Bappy Golder
13,449 PointsBappy Golder
13,449 PointsThanks Marcus. That's very helpful.
Marcus Parsons
15,719 PointsMarcus Parsons
15,719 PointsYou're very welcome, Bappy!
Brian Mendez
7,734 PointsBrian Mendez
7,734 PointsGreat question Bappy! Thanks for answering, Marcus.
Adam Akers
7,357 PointsAdam Akers
7,357 Pointsbest explanation I could find so far. Thanks Marcus