The first tends to be used for a few reasons:
- The name "sum" shows up in the
stacktrace which makes debugging
easier in many browsers.
- The name
"sum" can be used inside the
function body which makes it easier
to use for recursive functions.
- function declarations are "hoisted"
in javascript, so in the first case,
the function is guaranteed to be
defined exactly once.
Semicolon insertion causes
var f = function (x) { return 4; }
(f)
to assign 4 to f.
There are a few caveats to keep in mind though.
Do not do
var sum = function sum(x, y) { ... };
on IE 6 since it will result in two function objects being created. Especially confusing if you do
var sum = function mySym(x, y) { ... };
According to the standard,
function sum(x, y) { ... }
cannot appear inside an if block or a loop body, so different interpreters will treat
if (0) {
function foo() { return 1; }
} else {
function foo() { return 2; }
}
return foo();
differently.
In this case, you should do
var foo;
if (0) {
foo = function () { return 1; }
} ...