user1637281
user1637281

Reputation:

How to properly return an empty function?

I'm using a run-time assignment of functions to account for browser differences. However for un-supported browsers, I want to return an empty function so that a JavaScript error is not thrown.

But, jslint complains about empty functions. What is the jslint happy way to do this?

Empty block.

$R.functionNull = function () {
    // events not supported;
};

$R.Constructor.prototype.createEvent = (function () {
    if (doc.createEvent) {
        return function (type) {
            var event = doc.createEvent("HTMLEvents");
            event.initEvent(type, true, false);
            $NS.eachKey(this, function (val) {
                val.dispatchEvent(event);
            });
        };
    }
    if (doc.createEventObject) {
        return function (type) {
            var event = doc.createEventObject();
            event.eventType = type;
            $NS.eachKey(this, function (val) {
                val.fireEvent('on' + type, event);
            });
        };
    }
    return $R.functionNull;
}());

Upvotes: 16

Views: 40749

Answers (4)

Michal Červenka
Michal Červenka

Reputation: 171

What about returning

return () => undefined;

instead of

return $R.functionNull;

Upvotes: 2

splintor
splintor

Reputation: 10154

Use the lambda expression:

$R.functionNull = () => void 0;

Upvotes: 18

Nano Miratus
Nano Miratus

Reputation: 467

For me this works best:

emptyFunction = Function();

console.log(emptyFunction); // logs 'ƒ anonymous() {}'
console.log(emptyFunction()); // logs 'undefined'

It's so short that I wouldn't even assign it to a variable (of course you can also use a constant-like variable "EF" or so, that's even shorter and doesn't need the additioal "()" brackets). Just use "Function()" anywhere you need a truly empty function, that doesn't even have a name, not even when you assign it to a variable, and that's the small behaviour difference between my solution and Frédéric's:

// --- Frédéric ---

emptyFunction = function() {
   return undefined;
}

console.log(emptyFunction.name); // logs '"emptyFunction"'

// --- me ---

emptyFunction = Function();

console.log(emptyFunction.name); // logs '""' (or '"anonymous"' in chrome, to be fair)

Upvotes: 8

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262939

You can add a body to your function and have it return undefined:

$R.functionNull = function() {
    // Events not supported.
    return undefined;
};

This keeps the same semantics as a "truly empty" function, and should satisfy JSLint.

Upvotes: 15

Related Questions