The difference between the two functions? ("function x" vs "var x = function") [duplicate]

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

What's the difference between:

function sum(x, y) {
  return x+y;
}

// and 

var sum = function (x, y) {
    return x+y;
}

Why is one used over the other?


Solution 1:

The first is known as a named function where the second is known as an anonymous function.

The key practical difference is in when you can use the sum function. For example:-

var z = sum(2, 3);
function sum(x, y) {
    return x+y;
}

z is assigned 5 whereas this:-

var z = sum(2, 3);
var sum = function(x, y) {
    return x+y;
}

Will fail since at the time the first line has executed the variable sum has not yet been assigned the function.

Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition.

Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment.

Solution 2:

The first tends to be used for a few reasons:

  1. The name "sum" shows up in the stacktrace which makes debugging easier in many browsers.
  2. The name "sum" can be used inside the function body which makes it easier to use for recursive functions.
  3. function declarations are "hoisted" in javascript, so in the first case, the function is guaranteed to be defined exactly once.
  4. 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; }
  } ...