TIMEX
TIMEX

Reputation: 271654

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, ... ) 

Upvotes: 2

Views: 4021

Answers (5)

Bergi
Bergi

Reputation: 664297

Is there a builtin function 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))

Upvotes: 2

str
str

Reputation: 44969

You don't need the typeof at all. The terminology in this case is slightly strange but here is the explanation:

var v; // initialize variable v
if (v) {} // works although v has type "undefined"
if (notInitialized) {} // ReferenceError: notDefined is not defined

And it is the same when you have a function with parameters. The arguments are always initialized but might have the type undefined.

As a result, you can use either

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

or even

var process = function(next){
    next && next(a, b, c, d, e);
}

However, before actually calling next it might be a good approach to check whether it is actually a function.

If you are using ES6, you might also be able to use default parameters in case these work with your use case.

Upvotes: 1

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

It should be undefined and throws an error. Because you call a function named next and pass as argument to _call.

This is the right one :

_call(function('hello', 'world'){//do dtuff});

And

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

Upvotes: 0

derp
derp

Reputation: 2318

This is a bit of a hack but you might be able to use default arguments

(function(next=()=>{}){
    //do stuff
    next(a, b, c, d, e); 
})();

So if it is not called with an argument, next will be an empty function that doesn't do anything

Upvotes: 1

use this

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

Upvotes: 0

Related Questions