Question

I have the following code:

console.log(callback);
if (typeof callback != "undefined" || callback != null){
  callback();
}

where the console prints out:

null

but javascript is still attempting to execute the callback() function call. Any idea why?

Was it helpful?

Solution

Because it should be &&, i.e. logical AND:

if (typeof callback != "undefined" && callback != null) {
    callback();
}

But I'd suggest to use check for type "function":

if (typeof callback === "function") {
    callback();
}

or even shorter:

typeof callback === "function" && callback();

OTHER TIPS

try :

console.log(callback);
if (!(typeof (callback) == "undefined" || callback == null)){
  callback();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top