is
if( typeof myVar === "undefined" )
the same as
if( myVar===void(0) )
?
And what is the best pratice, if there is one between these ? Why ?
is
if( typeof myVar === "undefined" )
the same as
if( myVar===void(0) )
?
And what is the best pratice, if there is one between these ? Why ?
Quoting from MDN Docs for undefined
,
One reason to use
typeof
is that it does not throw an error if the variable has not been defined.// x has not been defined before if (typeof x === 'undefined') { // evaluates to true without errors // these statements execute } if(x === undefined){ // throws a ReferenceError }
However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is defined can be read by seeing whether it is defined in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object (using the in operator, for instance).
From the same document's void
section
var x;
if (x === void 0) {
// these statements execute
}
// y has not been defined before
if (y === void 0) {
// throws a ReferenceError (in contrast to `typeof`)
}
Conclusion
So, when you use typeof
to check if the variable's value is undefined
, it will not throw an exception. But direct comparison with undefined
or comparison with void 0
will throw an exception.