undefined is just not a reserved key phrase. As a substitute, it’s a property of the global object.
Earlier than ES5 (2009), it was attainable to change the
undefined international property, which might result in surprising habits for
undefined international might even occur in third get together code, e.g., libraries imported by way of the script tag. Since
void 0 all the time returns the precise primitive worth
undefined, it was generally used earlier than ES5 to make the code failsafe towards the re-definition of the
undefined international property.
The issue that
With ES5, the worldwide property
globalThis.undefined = "one thing else"; console.log(undefined); // prints undefined in trendy browsers
Nonetheless, whereas altering the
undefined international property is not attainable,
const undefined = "one thing else"; let test = aVariable === void 0; // void 0 is required right here
Having a neighborhood variable with the identify
undefined is a pitfall that you just need to keep away from. The ESLint rule no-undefined disallows the usage of undefined as a variable identify and prevents shadowing points.
void 0 is shorter than
Nonetheless, it’s best to depart fundamental code dimension optimizations to minifiers equivalent to Terser as a part of the product bundling course of. They will carry out many alternative optimizations, and the supply code stays extra readable with none guide code dimension optimizations like utilizing
void 0 as a substitute of
void 0 any longer:
- the worldwide property
undefinedcan’t be modified in ES5 and newer environments
- native variables with the identify
undefinedcould be disallowed with the ESLint rule no-undefined
- minifiers can exchange
void 0when creating the manufacturing bundle
Quite the opposite,
void 0 and course of completely different phrases (
undefined) for a similar idea (
TLDR: You should utilize
undefined and take away the pointless
void 0 complication.