JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1627
孤城傲影
孤城傲影 2020-11-22 00:59

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))



        
29条回答
  •  温柔的废话
    2020-11-22 01:32

    To contribute to the debate, if I know the variable should be a string or an object I always prefer if (!variable), so checking if its falsy. This can bring to more clean code so that, for example:

    if (typeof data !== "undefined" && typeof data.url === "undefined") {
        var message = 'Error receiving response';
        if (typeof data.error !== "undefined") {
            message = data.error;
        } else if (typeof data.message !== "undefined") {
            message = data.message;
        }
        alert(message); 
    }

    ..could be reduced to:

    if (data && !data.url) {
      var message = data.error || data.message || 'Error receiving response';
      alert(message)
    } 

提交回复
热议问题