0

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 ?

Flozza
  • 131
  • 2
  • 12

1 Answers1

1

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • You voted to close and then answered? – Ian Mar 18 '14 at 13:40
  • 1
    @Ian Yes. This piece of information was missing from that question. Perhaps, I should have added this information to the other answer? – thefourtheye Mar 18 '14 at 13:42
  • Hmm I guess technically. It's great information (especially if it's missing), it was just weird to me to put it in what will be closed as duplicate (hopefully). – Ian Mar 18 '14 at 14:09