Alex Rivera | Logout

JavaScript advantage by placing functions inside variables?

Asked 2011-02-16T23:06:16.693
10

I have seen recent code examples placing functions inside variables and then calling the functions like normal.

As in:

var myFunctionName = function() {
    Code Here...
}

myFunctionName();

I'm sure there are a lot of advantages with more advanced scenarios, but I'm just curious.

Edit
Report

1 Answer

13

There are no advantages, you aren't placing a function inside a variable you are simply naming the function differently.

function foo() { /* ... */ }
var foo = function () { /* ... */ }

These are exactly the same except for one thing.

This works:

foo("Hello!");
/* Later on... */
function foo() { /* ... */ }

This doesn't work:

foo("Hello!");
/* Later on... */
var foo = function () { /* ... */ }

The JavaScript interpreter will preprocess all function foo's before running and push them to the top of the program so they are available but won't do that with var foo = function's.

answered 2011-02-16T23:11:12.140

Your Answer