TIMEX TIMEX - 3 months ago 9
Javascript Question

How can I shorthand checking for undefined?

I have code like this:

var process = function(next){
//do stuff
if(typeof next != 'undefined') { next(a, b, c, d, e); }

}


I'm so sick of typing
typeof
everywhere. Is there a global function I can write that handles checking for undefined as well as all the arguments?

For example:

_call = function(next){
if(typeof next != 'undefined') next();
};


The above example doesn't work, by the way. Because node throws an error when I do this:

_call(next('hello', 'world')); //ERROR! next is undefined


So maybe I can do this?

_call(next, argument1, argument2, ... )

Answer

Is there a global function I can write that handles checking for undefined as well as all the arguments?

No, but you can write one yourself.

So maybe I can do this? _call(next, argument1, argument2, ... )

Yes:

function _call(fn, ...args) {
    if (typeof fn == "function") return fn(...args);
}

(using ES6 rest & spread syntax, in ES5 it would be fn.apply(null, Array.prototype.slice.call(arguments, 1))

Comments