Pergunta

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?

Foi útil?

Solução

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

Outras dicas

try :

console.log(callback);
if (!(typeof (callback) == "undefined" || callback == null)){
  callback();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top