The operator will check if the variable is really undefined.typeof
if (typeof variable === 'undefined') {
// variable is undefined
}
The operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.typeof
However, do note that will return . We have to be careful to avoid the mistake of initializing a variable to . To be safe, this is what we could use instead:typeof null
"object"
null
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison instead of simple equality , see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?===
==