5

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

In JavaScript we can say:

function a() {};

Or we could say

var a = function() {};

Can anyone explain to me how exactly these differ, which, if any, is more preferable, and under what circumstances would one use each?

Any links or external reading would also be much appreciated.

Community
  • 1
  • 1
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • As far as I know there is no difference, except that only the latter way can be used in objects. – pimvdb Jan 31 '11 at 19:40
  • 1
    @pimvdb there's a pretty big [difference](http://bonsaiden.github.com/JavaScript-Garden/#functions). – Raynos Jan 31 '11 at 19:43

3 Answers3

7

One is a function declaration and one is a function expression.

http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

Jason LeBrun
  • 13,037
  • 3
  • 46
  • 42
2

First

function a() {};

This can be either FunctionDeclaration or FunctionExpression. We can only knows if it's a FunctionDeclaration or a FunctionExpression, depending on the context where it appears.

example #1)

0,function a() {} //FunctionExpression

example #2)

(function a() {} ()); //FunctionExpression

example #3)

var b = function a() {}; //FunctionExpression

example #4)

foo(function a(){}); //FunctionExpression

Second

var a = function() {};

This is clearly a FunctionExpression for two reasons.

1) The right hand side of an assignment

2) anonymous function

useful links :

http://sweatte.wordpress.com/syntax/javascript-idioms-and-gotchas/

http://www.ecma-international.org/publications/standards/Ecma-262.htm

weirdFactory
  • 561
  • 5
  • 4
0

one is a function declaration the other is an object declaring a function. This is the basis of virtually every object oriented javascript tutorial.

brian brinley
  • 2,364
  • 1
  • 13
  • 10