Thanks for your answer. That helps me understand how they both work. I still need to understand in what circumstances you'd use the two different approaches and what the pros/cons of both are. – RichardDec 3 '08 at 11:42

Thanks for the examples, that really helped. – RichardDec 3 '08 at 12:01

Speaking about the global context, both, the var statement and a FunctionDeclaration at the end will create a non-deleteable property on the global object, but the value of both can be overwritten.

The subtle difference between the two ways is that when the Variable Instantiation process runs (before the actual code execution) all identifiers declared with var will be initialized with undefined, and the ones used by the FunctionDeclaration's will be available since that moment, for example:

Note: This answer has been merged from another question, in which the major doubt and misconception from the OP was that identifiers declared with a FunctionDeclaration, couldn't be overwritten which is not the case.

The two code snippets you've posted there will, for almost all purposes, behave the same way.

However, the difference in behaviour is that with the first variant, that function can only be called after that point in the code.

With the second variant, the function is available to code that runs above where the function is declared.

This is because with the first variant, the function is assigned to the variable foo at run time. In the second, the function is assigned to that identifier foo at parse time.

More technical info

Javascript has three ways of defining functions.

Your first snippet shows a function expression. This involves using the "function" operator to create a function - the result of that operator can be stored in any variable or object property. The function expression is powerful that way. The function expression is often called an "anonymous function" because it does not have to have a name,

Your second example is a function declaration. This uses the "function" statement to create a function. The function is made available at parse time and can be called anywhere in that scope. You can still store it in a variable or object property later.

The third way of defining a function is the "Function()" constructor, which is not shown in your original post. It's not recommended to use this as it works the same way as eval(), which has its problems.

In computer science terms, we are talking about anonymous functions and named functions. I think the most important difference is that an anonymous function is not bound to an name, hence the name anonymous function. In Javascript it is a first class object dynamically declared at runtime.

is syntax sugar, as the JavaScript parser creates a property that attaches to the call object if the function is defined inside another function, and to the global object in the other cases; as it is the parser to do that, I think the term "syntax sugar" is correct.