Problem
When checking whether a value is undefined, do you want to test it?
I would test it like this before.
function isUndefined(obj){ return obj === undefined;}
But when I recently read the book javascript framework design, he used another method and I was a little confused.
function isUndefined(obj){ return obj === void 0;}
Which of the two is better? How can we compare them? It should be compared from its applicability and browser compatibility! Then I found the definition of the void operator and the undefined description in the MDN to find out that the method in javascript framework design is better. Why? The following describes
Description
-
Void
-
The void operator evaluates the given expression and then returns undefined. That is to say, void is an operator and it always returns The undefined value.
-
Undefined
-
The global undefined property represents the value undefined. That is to say, undefined is actually a global variable, which represents undefined. We can use
window.hasOwnProperty("undefined");
If true is returned, it is a global variable. Since it is a global variable, We can modify it. ES3 and ES5 are different in modifying some specific variables. Each variable in ES3 is writable and configurable and can be traversed, but ES5 sets some APIs to set these features of variables. You can use this code on the chrome (ES5 supported) console.
Object.getOwnPropertyDescriptor(window,"undefined")
We can see that
Object {value: undefined, writable: false, enumerable: false, configurable: false}
. We can see that the undefined value in ES5 cannot be modified (that is, writable is false), but in the old browsers such as IE7 and 8, you can modify the undefined value, as a result, your isUndefined has no effect.
Why void 0, specifically?
One problem with the stackoverflow website is that you must use void 0? Cannot it be void 1, void 10000, void "hello world" or something else? The answer is yes, but 0 gives people the feeling that they are short and common.
Referenceundefined
Void
What does void 0 mean?