<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">JavaScript: var functionName = function() {} vs function functionName() {}</a>  </p>
</blockquote>



<p>What's the difference between:</p>

<pre><code>function sum(x, y) {
  return x+y;
}

// and 

var sum = function (x, y) {
    return x+y;
}
</code></pre>

<p>Why is one used over the other?</p>

The first one is a named function statement, the second one assigns an anonymous function expression to a variable.
The function statement is added to its scope immediately - you don't need to run it before being able to call it, so this works:
```
```
var y = sum(1, 2);

function sum(x, y) {
   return x + y;
}
```
```
But the function expression is only assigned to the variable when the code is executed, so this doesn't work:
```
```
// Error here because the function hasn't been assigned to sum yet.
var y = sum(1, 2);

var sum = function(x, y) {
   return x + y;
}
```
```
An advantage of the expression form is that you can use it to assign different functions to the expression at different points - so you can change the function, or use a different one under different conditions (such as depending on the browser being used).
An advantage of a named function statement, is that debuggers will be able to display the name. Although, you can name function expressions:
```
```
var sum = function sum(x, y) {
   return x + y;
}
```
```
But this can be confusing since the two names are actually in different scopes and refer to different things.