Reputation: 1696
What is the difference between these?
var myFunc = function() {
// ...
};
vs.
var myFunc = function myFunc() {
// ...
};
In the 2nd example, arguments.callee.caller.name
works, but not in the first one. Is there anything wrong with the 2nd syntax?
Upvotes: 2
Views: 1506
Reputation: 11582
The name
in a function literal is optional, if omitted as in the first case you show the function is said to be anonymous.
This is from JavaScript: The Good Parts by Douglas Crockford:
A function literal has four parts. The first part is the reserved word function. The optional second part is the function's name. The function can use its name to call itself recursively. The name can also be used by debuggers and development tools to identify the function. If a function is not given a name, as shown in the previous example, it is said to be anonymous.
Upvotes: 3
Reputation: 94101
The second one has a name while the first one doesn't. Functions are objects that have a property name
. If the function is anonymous then it has no name.
var a = function(){}; // anonymous function expression
a.name; //= empty
var a = function foo(){}; // named function expression
a.name; //= foo
Upvotes: 7
Reputation: 887285
The first function doesn't have a name.
Assigning a function to a variable doesn't give the function a name.
Upvotes: 1