15

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;
}());
  • [JSHint](http://jshint.com/) has an option to tolerate empty blocks, I do not think jslint has that option. – epascarello Jun 10 '13 at 14:27
  • Jslint like things to be explicit and easy to read, hence I think it expects you to return undefined. –  Jun 13 '13 at 16:38

4 Answers4

15

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.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
14

Use the lambda expression:

$R.functionNull = () => void 0;
splintor
  • 9,924
  • 6
  • 74
  • 89
8

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)
Nano Miratus
  • 467
  • 3
  • 13
2

What about returning

return () => undefined;

instead of

return $R.functionNull;

  • Just a sidenote for others: () => void 0; as seen in splintor's answer is safer because it always returns undefined and cannot get overriden. I had to learn that the hard way... – aProgger Nov 19 '21 at 17:58