Aside from the obvious preventing of links being clicked (with javascript:void(0);) and for the definition of undefined in many javascript precompiled languages like coffeescript (where undefined becomes void 0) –> What else can the void function be used for?
Related: What does "javascript:void(0)" mean?
Useful Link: MDN page for void
First,
voidis 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:Theoretical use:
Change the return value of an expression that produces side effects.
But this use is not very valuable in most situations.
Practical uses:
We already know about:
undefined– Since the global variableundefinedcould be modified (it is not a reserved word),void 0is a more reliable way to get anundefinedvalue. Eg:obj.foo === void 0Other 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
undefinedto 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 ofundefined:Your console output would be:
Does JavaScript need this operator? Probably not. You can get the same functionality (and more) from a self invoking anonymous function:
But that’s not quite as concise.