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 The $.param( ) inverse function in JavaScript / jQuery

Community
  • 1
  • 1
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

1 Answers1

6

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
  • 687,336
  • 108
  • 737
  • 1,005