The first one creates an anonymous (nameless) function and assigns it to a variable called foo
. The second one declares a function with the name foo
. Usually those two forms can be used pretty interchangeable but there are still some differences. The following two are the main differences that come to my mind. The first one might be responsible for what you are experiencing:
Hoisting
In the second example, the complete function definition will be hoisted up to the top of the current scope. So when you write:
var a = new A();
function A() {}
JavaScript will interpret this as:
function A(){}
var a;
a = new A();
...and your code will work fine.
In the first example however, only the variable declaration will be hoisted up. The function body stays where it is. So this:
var a = new A();
var A = function(){};
will be interpreted as this:
var a, A;
a = new A();
A = function(){};
which will lead to an error, since A
is still undefined by the time you try to create an instance.
The name property
As I said, the first one creates an anonymous function. That means, if you try to access the name
property of that function it will return an empty string:
var A = function(){};
console.log(A.name) //{empty string}
In the second example, your function has the actual name A
:
function A(){}
console.log(A.name) //A