Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
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)
}