The most compelling reason for having it in the language, seems to be for its use in javascript: URLs, such as in the href attribute of an <a> tag (example from this MDN article):
<a href="javascript:void(document.body.style.backgroundColor='green');">
Click here for green background
</a>
The code in a javascript: URL is evaluated as an expression, and the result ─ if it is not undefined ─ is used (as a string), as the link URL in this case. But here, the assignment expression produces the string 'green', which is not supposed to be a link address; so the void operator is needed to discard that string, so the browser doesn't navigate away from the page when the link is clicked.
The same applies to javascript: links loaded directly in the address bar, from the browser's bookmarks or history, or otherwise. Discarding the values produced by these links is confirmed as the actual reason for having the void operator, in an email from Javascript creator Brendan Eich (web.archive.org link):
In particular, I made it possible to generate a new document by loading, e.g. javascript:'hello, world', but also (key for bookmarklets) to run arbitrary script against the DOM of the current document, e.g. javascript:alert(document.links[0].href). The difference is that the latter kind of URL use an expression that evaluates to the undefined type in JS. I added the void operator to JS before Netscape 2 shipped to make it easy to discard any non-undefined value in a javascript: URL.
MDN suggests a couple other possible uses for the void operator, but they aren't so compelling:
- It allows an IIFE to be used where a statement would be expected; but parentheses also work for this.
- It allows discarding the result of an arrow function when a callback should be provided which doesn't leak a return value; but braces around the body of the arrow function also work for this.
Other proposed uses include it being a reliable way to get an undefined value before the global constant undefined was added to the language, and it being a way to silence linter warnings about unused results of some operations.
(void)foo(bar);, which would ignore the return value offooand (usually) suppress a diagnostic about unused value. $\endgroup$(void)is an operator in C, both semantically, and in the terminology of the language spec. It has an effect substantially analogous to JS'svoidoperator. How is it relevant that C also has other cast operators? $\endgroup$