We are frequently using the following code pattern in our JavaScript code
if (typeof(some_variable) != \'undefined\' && some_variable != null)
{
Since there is no single complete and correct answer, I will try to summarize:
In general, the expression:
if (typeof(variable) != "undefined" && variable != null)
cannot be simplified, because the variable
might be undeclared so omitting the typeof(variable) != "undefined"
would result in ReferenceError. But, you can simplify the expression according to the context:
If the variable
is global, you can simplify to:
if (window.variable != null)
If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:
if (variable != null)
If it is object property, you don't have to worry about ReferenceError:
if (obj.property != null)
Open the Developer tools in your browser and just try the code shown in the below image.
Checking null with normal equality will also return true for undefined.
if (window.variable == null) alert('variable is null or undefined');
You can just check if the variable has a value or not. Meaning,
if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false
}
If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.
if( typeof myVariable !== 'undefined' ) {
// myVariable will get resolved and it is defined
}
You must define a function of this form:
validate = function(some_variable){
return(typeof(some_variable) != 'undefined' && some_variable != null)
}
In ES5 or ES6 if you need check it several times you cand do:
const excluded = [null, undefined, ''];
if (!exluded.includes(varToCheck) {
// it will bee not null, not undefined and not void string
}