Larry Gerndt
Larry Gerndt

Reputation: 1925

Is it safe to name an anonymous function?

With Promises trending up, we often see this:

getSomeData.then(
        // success
    function(data) {
        ...
    },
        // failure
    function(error) {
        ...
    }
);

Those comments could be helpful to newbies, but I would much prefer to name the anonymous functions, like this:

getSomeData.then(
    function success(data) {
        ...
    },
    function failure(error) {
        ...
    }
);

Naming an anonymous function, in this case, makes sense, but is it safe? I've seen older posts here that reference this article as a warning about IE, but does anyone know if this is still an issue with IE9?

Upvotes: 2

Views: 146

Answers (1)

Rob W
Rob W

Reputation: 349222

Yes, it's safe 1 to use named function expressions. The bug you're mentioning does not exist in IE9 any more (it does in IE8 though).

Another advantage of the named expression is for debugging. Instead of (anonymous), you will see a meaningful name.

1
For the ones who don't know: In Internet Explorer up to and including version 8, the named variable would leak in the following code:

var expressionName = function shouldNotLeak() {};
shouldNotLeak(); // Error in all browsers except for Internet Explorer <= 8

Upvotes: 5

Related Questions