0

What is the difference between these two functions;

 var a = function () { console.log("hi");  }  
 var b = function xyz() { console.log("hi");  }  

When i call these two functions both are giving same result. Then what is point in declaring function name 'xyz' ?

balaphp
  • 1,306
  • 5
  • 20
  • 40
  • 'a' is an anonymous function while you are assigning to 'b' a function called xyz –  Sep 08 '14 at 03:37

1 Answers1

0

The second form is called a "named function expression". It gives you several benefits over normal function expressions:

  • It makes it a bit easier to debug -- when you have a bunch of functions like those, and you get an error, naming your functions makes it a bit easier to interpret the resulting stack trace.
  • You can call named functions recursively -- for example, doing:

    f = function f() {
        f();
    };
    
    f();
    

    ...works.

You can find more detailed information here.

Using named function expressions also comes with some disadvantages. For example, doing f = function g() { ... } will actually create two entities -- the functions f and g, which can potentially be confusing. (see comments) There are also some intricacies with scoping which can potentially cause bugs if you're not careful. You can find more detailed information here.

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
  • 2
    The expression `f = function g() {...}` no longer appears to "leak" g into the enclosing namespace. That post was written in 2012 and I believe some updates were made regarding that. I played around with some of his code here: http://jsfiddle.net/shashank92/uk7buehf/ – Shashank Sep 08 '14 at 03:58
  • Yeah, creating two instances was only a bug in older IE versions. – Felix Kling Sep 08 '14 at 04:18
  • `var test = function (){ console.log(1); test(); } test();` This one also recursive.... – balaphp Sep 10 '14 at 05:52