Search code examples
javascriptnullundefinedconditional-statementsor-operator

javascript - object not a function error when evalulating whether something is null


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?


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();