tags:

views:

50

answers:

1

In Javascript, I have seen

var QueryStringToHash = function QueryStringToHash  (query) {
    ...
}

What is the reason of writing that instead of just

function QueryStringToHash(query) {
    ...
}

?

This comes from the answer in http://stackoverflow.com/questions/1131630/javascript-jquery-param-inverse-function

+6  A: 

Declaring a function means that it's defined when the script block is parsed, while assigning it to a variable is done at runtime:

x(); // this works as the function is defined before the script block is executed

function x() {}

but:

x(); // doesn't work as x is not assigned yet

var x = function() {}

Assigning a function to a variable can be done conditionally. Example:

var getColor;
if (color == 'red') {
  getColor = function() { return "Red"; }
} else {
  getColor = function() { return "Blue"; }
}
Guffa