The most compelling reason for having it in the language, seems to be for its use in
href attribute of an
<a> tag (example from this MDN article):
Click here for green background
The code in a
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
In particular, I made it possible to generate a new document by loading, e.g.
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
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.