0

Possible Duplicates:
When to use anonymous JavaScript functions?
Is there any difference between var name = function() {} & function name() {} in Javascript?

in javascript (and other scripting languages) what is the 'real' difference between these two syntax:

a) function myFun(x) { yadda yadda }

b) myFun(x) = function { yadda yadda }

to a casual observer - no 'real' difference - you still call either as myFun()...and they still return the same thing, so if reference and return are identical - is it a preference or is there some difference in the code parsing engine that treats these two differently - and if so - when would you use one over the other???

Community
  • 1
  • 1
j-p
  • 3,698
  • 9
  • 50
  • 93
  • 4
    I don't think your second example is valid? It should be `var myFun = function (x) { yadda yadda }` – jishi Jun 23 '11 at 13:44
  • @Other closers you chose the wrong "dup," tsk. http://stackoverflow.com/search?q=%5Bjavascript%5D+%22named+function+expressions%22 – Matt Ball Jun 23 '11 at 13:46

2 Answers2

2

The real, super-secret difference:

foo(); // succeeds
function foo() { alert("hi"); }

bar(); // fails
var bar = function() { alert("hi"); }

The former syntax hoists the function such that (although arguably bad practice) it can be called before its actual line in the code. The latter syntax requires you to declare the function first.

brymck
  • 7,555
  • 28
  • 31
  • 1
    I find this explanation more elegant than http://stackoverflow.com/questions/6223050/when-to-use-anonymous-javascript-functions/6223095#6223095 (assuming the OP is aware of what not using `var` does – ninjagecko Jun 23 '11 at 13:47
0

You actually mean var myFun = function(x) { ... }.

If you don't put the var there (bad), it becomes a global variable, which is not what you want. The function syntax will automatically restrict the variable to be a local I think, but people use both syntaxes.

Otherwise the difference is so minor that it is not worth caring about, but you can see the accepted answer on When to use anonymous JavaScript functions?

Community
  • 1
  • 1
ninjagecko
  • 88,546
  • 24
  • 137
  • 145