The void operator evaluates an expression and returns the primitive value undefined.
void 0 evaluates
0, which does nothing, and then returns
undefined. It is effectively an alias for
Why is void 0 used as an alias for undefined?
undefined is not a reserved keyword. Instead, it is a property of the global object.
Before ES5 (2009), it was possible to modify the
undefined global property, which could lead to unexpected behavior for
undefined global could even happen in 3rd party code, e.g., libraries imported via the script tag. Since
void 0 always returns the actual primitive value
undefined, it was commonly used before ES5 to make the code failsafe against the re-definition of the
undefined global property.
The global property 'undefined' after ES5
The problem that
With ES5, the global property
globalThis.undefined = "something else"; console.log(undefined); // prints undefined in modern browsers
Undefined can still be shadowed by a local variable
However, while changing the
undefined global property is no longer possible,
const undefined = "something else"; let check = aVariable === void 0; // void 0 is needed here
Having a local variable with the name
undefined is a pitfall that you want to avoid. The ESLint rule no-undefined disallows the use of undefined as a variable name and prevents shadowing issues.
Can void 0 help reduce the bundle size?
void 0 is shorter than
However, it is best to leave basic code size optimizations to minifiers such as Terser as part of the product bundling process. They can perform many different optimizations, and the source code remains more readable without any manual code size optimizations like using
void 0 instead of
void 0 any longer:
- the global property
undefinedcannot be changed in ES5 and newer environments
- local variables with the name
undefinedcan be disallowed with the ESLint rule no-undefined
- minifiers can replace
void 0when creating the production bundle
On the contrary,
void 0 and process different terms (
undefined) for the same concept (
TLDR: You can use
undefined and remove the unnecessary
void 0 complication.
Top comments (0)