The void
operator evaluates the given expression and then returns undefined
.
void expression
undefined
The void
operator is often used to obtain the undefined
primitive value, by means of writing void 0
or void(0)
. Note that void
is an operator, not a function, so ()
is not required.
Usually the result of a void
expression and undefined
can be used interchangeably.
However, in older versions of ECMAScript, window.undefined
could be assigned any value, and it is still possible to use undefined
as name for function parameters variables inside functions, thus disrupting other code that relies on the value of undefined
.
void
will always yield the true undefined
value though.
void 0
is also commonly used in code minification as a shorter way of writing undefined
. In addition, it's probably safer as some other code could've tampered with window.undefined
.
Returning undefined
:
function foo(){
return void 0;
}
console.log(foo()); // undefined
Changing the value of undefined
inside a certain scope:
(function(undefined){
var str = 'foo';
console.log(str === undefined); // true
})('foo');