First, void
is an operator, not a function. The answer to your question can't be given any more clearly than the explanation given in the link to MDN you provided in your question:
Summary
The void
operator evaluates the given expression and then returns undefined
.
...
Uses
This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined
is desired.
Theoretical use:
Change the return value of an expression that produces side effects.
var i;
i = 0; // returns 0
void i = 1; // returns undefined
But this use is not very valuable in most situations.
Practical uses:
We already know about:
- Cancel navigation in a bookmarklet
- Compare item to
undefined
- Since the global variable undefined
could be modified (it is not a reserved word), void 0
is a more reliable way to get an undefined
value. Eg: obj.foo === void 0
Other uses:
Prevent verbose console output - I use it in a JavaScript console when I only want to execute some code and don't want to pollute the console with uninteresting verbose output.
Explicitly pass undefined
to a function - It can be useful to know whether a function was called without passing arguments, or whether an argument was passed to a function with a value of undefined
:
function countArguments(a) {
console.log(a === undefined);
console.log(arguments.length);
}
countArguments();
countArguments(void 0);
Your console output would be:
true
0
true
1
Does JavaScript need this operator? Probably not. You can get the same functionality (and more) from a self invoking anonymous function:
(function(){ /* expression */ })()
But that's not quite as concise.