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

1 Answer 1

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"; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.