Avoid Void Operator
ID |
javascript.avoid_void_operator |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
JavaScript |
Tags |
code-smell, simplification |
Description
Reports the unary void operator where its result is read. void evaluates its operand and then throws the value away, always yielding undefined, so any expression built on it is a constant that does not look like one.
const result = void compute(); // FLAW — result is undefined, whatever compute returned
if (void ready) { } // FLAW — the condition can never be true
function pick(flag, value) {
return flag ? void reset() : value; // FLAW
}
Two idioms are exempt, because they are what the operator is used for today:
const nothing = void 0; // OK — the legacy spelling of undefined
void fetchLatest(); // OK — a deliberate discard, as a statement
button.onclick = () => void save(); // OK — a discard in an arrow body
Rationale
-
void 0predatesundefinedbeing safe to name — before ES5 it was a writable global — and still appears in code that has to run everywhere. It is a constant, not a discarded computation, so it carries none of the confusion this rule is about. -
A
voidwhose own value goes nowhere, either as a statement or as the whole body of an arrow function, is the accepted way to say "this returns a promise on purpose and I am not awaiting it". -
What is left is the shape worth reporting. To see that
const result = void compute()always assignsundefined, the reader has to know thatvoiddiscards — and the operator is rare enough that most readers do not.