Use Case 1
In my code, I always have ESLint's no-floating-promises
enabled, which makes sure that I never forget to await a promise (flashback to the hours of debugging I've spent only to find that's what it was).
However, sometimes there are also promises that I want to leave unawaited, to let them run in the background. In those cases the void
keyword makes it look to ESLint as though the promise is being consumed, when it really isn't:
fetch('https://google.com/') // ESLint error: no-floating-promises
void fetch('https://google.com/') // Does the same thing; no ESLint error
Use Case 2
In other people's code, you'll often see it in combination with the literal 0
:
{ code: "function foo() { if (true) return; else return void 0; }", options: [{ treatUndefinedAsUnspecified: true }] },
--------------------------------------------------------^^^^^^ HERE
This can be done for one of two reasons:
- See @sabithpocker's answer: Because
undefined
can be shadowed and void
cannot. Especially useful when code is mixed with arbitrary user code, for example in an optimizer; where it's conceivable the user may have created a variable named "undefined".
- Because
void 0
is shorter than undefined
. Especially in compiled code (for example if it's been passed through terser or webpack), it's important to minimize the amount of characters in the bundle. void 0
has 6 characters, while undefined
has 9, so it's an easy three character win for the optimizer to replace all instances of undefined
with void 0
.
TL;DR: The void keyword can be used to:
- Escape certain linter rules
- Replace
undefined
with void 0
to save three characters
<script>
tag, which I am aware of. I'm more curious about the use within a script itself. – Branchingnpm
module.console.log
is a poor example. – Branchingvoid
being used in,eslint
is one amongst them – Branchingvoid
when I know an argument to a function is unused to avoid the unused var "warning" – Salopif (...) return f(...)
. It would be cleaner to doif (...) return void f(...)
rather than have my function's return value depend on another's. – Diaphanous