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 trialRifqi Fahmi
23,164 Pointsneed little help here about function
in this javascript course we can see the teacher write function like this
function passwordEvent(){
//Find out if password is valid
if(isPasswordValid()) {
//Hide hint if valid
$password.next().hide();
} else {
//else show hint
$password.next().show();
}
}
And he call the function in this function
$password.focus(passwordEvent).keyup(passwordEvent);
I am little forget about last lesson in javascript, I remember that whenever we call the function, we need to type the-function-name(). Why in this video he didn't type the parentheses after calling the function such as .......focus(passwordEvent)......
Maybe i am missing something in learning javascript, thanks :)
1 Answer
Jason Anello
Courses Plus Student 94,610 PointsHi Rifqi,
You're correct. When calling a function you need to put parentheses after the name. In this case though, we don't want to call the function right then and there.
If we have the following:
.focus(passwordEvent()) // wrong code
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 what we want to happen.
Instead we want to pass in a reference to the function (name only, no parentheses) so that the focus method can call this function for us anytime the element receives focus.
We're basically saying to the focus method, "Here's the name of the function that I want you to call whenever the element receives focus."
Rifqi Fahmi
23,164 PointsRifqi Fahmi
23,164 Pointsthanks jason, thats make myself clear :D
Fidel Severino
3,514 PointsFidel Severino
3,514 PointsWow, thanks for that explanation. I was wondering the same thing. Very informative answer!