2

What is the difference between

var a = function() {}

and

var a = function b() {}

The latter, b is undefined?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Thịnh Phạm
  • 2,528
  • 5
  • 26
  • 39

3 Answers3

4

The second one is a named anonymous function - the name will appear in a stacktrace (otherwise in the stacktrace you''ll see just "anonymous function")

Community
  • 1
  • 1
Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
4

The first is an anonymous function expression and the second a named function expression, both valid in Javascript.

For example, it can be used for recursion without arguments.callee (deprecated and not permitted in strict mode), because it refers to itself, no matter where. The scope of the reference is local only to inside the function, that is it isn't accessible globally:

var a = function b(){
    return b;
 };
function c() {
    return c;
}
var d = function e() {
    return e();
};
d(); // maximum call stack size exceeded :P
var f = c;
c = null;
f(); // null
a(); // function
b();// undefined not a function
b; // not defined
a()(); // same function again
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
  • 1
    One more thing you forgot from your example: `a()()` which calls the returned "b" (which in this case is itself so it's just a bit silly, but informative nonetheless) – slebetman Oct 03 '13 at 09:06
1
var a = function() {}

Function name can be omitted. In this case function name is omitted. These functions are called anonymous functions.

Read about javascript scope and anonymous function advantages and disadvantages for details.

Bridge
  • 29,818
  • 9
  • 60
  • 82