This is happening due to hoisting.
In your first case, the code is interpreted as (notice how the function declaration is being evaluated first):
function showAlert() {
alert( "Hiya" );
}
$("#clickme").click( showAlert );
And your second is interpreted as :
var showAlert;
$("#clickme").click( showAlert );
showAlert = function() {
alert( "Hello" );
}
Since showAlert
is a variable declaration and not a function declaration (notice the var
keyword), the variable declaration is evaluated first, and by the time you bind the event handler, the showAlert
variable is declared, but it holds the undefined
value.
This is what hoisting does : it hoists variable and function declarations to the top of the closure.
There are a couple of good resources on hositing out there, including here on SO.