difference between "void 0 " and "undefined"
From MDN:
The
void
operator evaluates the givenexpression
and then returnsundefined
.This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.
The void operator is often used merely to obtain the
undefined
primitive value, usually using "void(0)
" (which is equivalent to "void 0
"). In these cases, the global variableundefined
can be used instead (assuming it has not been assigned to a non-default value).
Closure Compiler swaps in void 0
because it contains fewer characters than undefined
, therefore producing equivalent, smaller code.
Re: OP comment
yes, I read the documentation, but in the example I gave, "google closure" in a case using "void 0" and another "undefined"
I believe this is actually a bug in Google Closure Compiler!
The real only semantic difference between void expr
and undefined
is that on ECMAScript 3, the undefined
property of the global object (window.undefined
on browser environments) is writable, whereas the void
operator will return the undefined
value always.
A popular pattern that is often implemented, to use undefined
without worries is simply declaring an argument, and not passing anything to it:
(function (undefined) {
//...
if (foo !== undefined) {
// ...
}
})();
That will allow minifiers to shrink the argument maybe to a single letter (even shorter than void 0
:), e.g.:
(function (a) {
//...
if (foo !== a) {
// ...
}
})();
Just a follow-up on all the answers before.
They look the same, but to the Compiler they are completely different.
The two code sections compile to different outputs because one is referring to a local variable (the var undefined), and the compiler simply in-lines it because it is used exactly once and is no more than one line. If it is used more than once, then this in-lining won't happen. The in-lining provides a result of "undefined", which is shorter to represent as "void 0".
The one without a local variable is referring to the variable called "undefined" under the global object, which is automatically "extern'ed" by the Closure Compiler (in fact, all global object properties are). Therefore, no renaming takes place, and no in-lining takes place. Voila! still "undefined".