25

Is there any difference between

function MyFunc() {
    // code...
}

and

var MyFunc = function() {
    // code...
};

in JavaScript?

altso
  • 2,311
  • 4
  • 26
  • 40

3 Answers3

9

I know that a difference between them is that named functions work everywhere regardless you declare them, functions in variables don't.

a();//works   
function a(){..}

works

a();//error
var a=function(){..}

doesn't work but if you call it after the declaration it works

var a=function(){..}
a();//works
gsamaras
  • 71,951
  • 46
  • 188
  • 305
mck89
  • 18,918
  • 16
  • 89
  • 106
7

This article might answer your question : JavaScript function declaration ambiguity.

Only the first one is an actual function declaration, whereas the shorthand method is just a regular variable declaration with an anonymous function assigned to it as its value.

(look at the comments, too, which might get some useful informations too)

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
-1

There is no difference superficially, so you can use both formats in your code.

To js interpreter it is different though.

First one is a named funciton.

Second one is an anonymous function that gets assigned to a variable.

Also, while debugging, you won't get a name of for the second function in stack trace.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Aaron Qian
  • 4,477
  • 2
  • 24
  • 27