I'm looking for a way to do the following:
var test = 'I exist!';
var testNull = null;
var testUndefined;
function checkVar(varToCheck) {
return typeof varToCheck != 'undefined' && varToCheck != null;
}
console.log(checkVar(test)); // Logs true
console.log(checkVar(testNull)) // Logs false
console.log(checkVar(testUndefined)) // Logs false
console.log(checkVar(undefinedVar)) // Logs false
When it tries to execute the last line, instead of false
, this throws an error: Uncaught ReferenceError: undefinedVar is not defined
.
I know it can be done with:
if (typeof varToCheck != 'undefined' && varToCheck != null) {
alert('something happens!')
}
but it's becoming annoyingly repetitive to use long conditions in my project, once I have a lot of variables to check. Any ideas?