0

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

Why does this work...

$("#clickme").click( showAlert );

function showAlert() {
  alert( "Hiya" );
} 

... but not this...?

$("#clickme").click( showAlert );

var showAlert = function() {
    alert( "Hello" );
}
Community
  • 1
  • 1
Xoundboy
  • 827
  • 15
  • 26

2 Answers2

4

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.

Community
  • 1
  • 1
gion_13
  • 41,171
  • 10
  • 96
  • 108
  • Here is another good article on [**JavaScript hoisting**](http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/). +1 – Aust Nov 20 '12 at 23:07
  • thanks for reminding me about hoisting - I actually knew this already from using jslint but maybe because the var declaration was a function I didn't realise that it applied. – Xoundboy Nov 20 '12 at 23:22
3

The first is a Function Declaration..

The second is a function Expression..

Function Declarations are first read before any code is executed.

So the first case works . The second method does not work as that was not defined yet by the time the function is being assigned to it,..

So this will work

var showAlert = function() {
    alert( "Hello" );
}

$("#clickme").click( showAlert );

i.e, defining the function and then assigning the handler

Sushanth --
  • 55,259
  • 9
  • 66
  • 105