0

I have this code:

function myFunction(){
    alert("Hello");
}

And this other code:

var myFunction = function(){

}

What is the difference?

Yang
  • 8,580
  • 8
  • 33
  • 58
Isma Haro
  • 263
  • 6
  • 16
  • 4
    http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname – Yang Jun 03 '15 at 21:40

2 Answers2

2

The first is the normal way to declare a function in javascript. You call it by referring to its name, myfunction().

The second is an anonymous function that is stored in a variable as functions are first class citizens in javascript. The variable myfunction now holds the anonymous function.

Basically the first is a normal function while the second is a variable holding an anonymous function.

David
  • 413
  • 6
  • 13
0

The first is a named function, which if you were to look at a stack trace, you'd see myFunction when it was called.

The second is a variable set to an anonymous function. In a stack trace, this function would have an <anonymous> as it's name, making it harder to trace when there are many anonymous functions.

Christian Grabowski
  • 2,782
  • 3
  • 32
  • 57
  • While your statement is true, it gives the impression that using anonymous function is bad. It is not, and there are many arguments for it. Worst case, it is debatable. – Ortiga Jun 03 '15 at 21:47
  • I never said it was bad, just hard to debug haha, there are plenty of times when to use both, and both even together. In fact anonymous functions are great for providing scope, I'm trying to get at self-instantiation with that. – Christian Grabowski Jun 03 '15 at 21:48
  • No problem, as I said, it gave the impression. I just wanted to make it clear for a beginner that might read your comment and think that they should never use anonymous functions. – Ortiga Jun 03 '15 at 21:54