Possible Duplicate:
What is the difference between a function expression vs declaration in Javascript?
Is there a MAJOR difference between declaring functions in these ways:
-
function foo(){ alert('BAR'); } -
var foo = function (){ alert('BAR'); } -
var foo = function bar(){ alert('BAR'); }
I was told here that:
It happens at a different time, and results in a variable referring to an anonymous function. A function declaration happens prior to any stepwise code executing in the scope, and results in both a binding and a function with a proper name.
Can the way I declare my function really affect the efficiency of my code, and if so which way is best to use?
Yes, there is a major difference.
The first is a function declaration. It happens upon entry to an execution context, prior to any step-by-step code being processed. It cannot be within any kind of control block (e.g., it’s not legal in the body of an
ifstatement; however, most browsers will try to accommodate it if you do that — sometimes resulting in very surprising behavior — at variance with the spec). It results in a named function.The second is a function expression (specifically, an anonymous function expression). Like all expressions, it’s processed when it’s encountered in the step-by-step execution of the code. And like all expressions, it can be within a control block. It results in a function with no name assigned to a variable that has a name.
The third is a named function expression. It’s a function expression like the above, but the function is also given a name. You want to avoid these with IE8 and earlier, since IE will actually get it quite wrong, creating two separate functions (at two different times). (Basically, IE treats it as both a function declaration and a function expression.) IE9 finally gets this right.
Note that your second and third examples rely on automatic semicolon insertion; because those are both assignment statements, they should end with a
;(after the ending}of the function).