Skip to content Skip to sidebar Skip to footer

In Javascript, What Is The Motivation Or Advantage Of Using Var Foo = Function Foo(i) { ... }?

I see that in the answer of In Javascript, why write 'var QueryStringToHash = function QueryStringToHash (query) { ... }'? which is doing something like var foo = function foo(p

Solution 1:

In shortly, if you take the following code, the first example creates a function, named foo, the second example creates an anonymous function and assign it to bar variable. Besides style, the basic difference is that foo can be called, in code, before it's definition (since it's the name of the function); otherwise, bar is an undefined variable before it receives the assignment, thus cannot be used before.

var foo_result = foo(123); // okfunctionfoo(param) { /* ... */ }

var bar_result = bar(123); // error: undefined is not a functionvar bar = function(param) { /* ... */ }
var bar_result = bar(123); // ok

I'd recommend you to read the suggestion of @Pekka.

Post a Comment for "In Javascript, What Is The Motivation Or Advantage Of Using Var Foo = Function Foo(i) { ... }?"