preface
If you’ve seen scaffolding compiled code, you’ll see that all expressions involving undefined are compiled to void 0, for example
/ / the source code
const a: number = 1
a === undefined
/ / the compiled
"use strict";
var a = 1;
a === void 0;
Copy the code
Void and undefined
-
Undefined is a base type and a global property
console.log(window.hasOwnProperty('undefined')) //true console.log(window.undefined) //undefined Copy the code
In javascript, global properties are allowed to be overridden, as you can
window.undefined = 1 Copy the code
-
Void is an operator (like Typeof) that can only evaluate an expression, not assign it, for example
var typeof = 1 //Uncaught SyntaxError: Unexpected token 'typeof' Copy the code
Void 0 replaces undefined
- Security assignment
From the above distinction, it can be seen thatvoid 0
To take the place ofundefined
Assignment is actually safer, so almost all scaffolding tools incorporate the ability to convert undefined to void 0 - shorter
void 0
contrastundefined
The browser transfer process has fewer bytes
So is this the case?
- A more secure
The fundamental reason is that before ECMAScript 5,undefined
As a global property, it can be read and written, and some poor quality libraries will overwrite the value of undefined, causing the direct assignment of undefined to be incorrect. After ECMAScript 5,undefined
Set it to read only, and you don’t have the problems described above, and you don’t have much of an issue with compatibility.
- shorter
Personally think write source code scenarios must be usedvoid 0
Instead ofundefined
Reading can bring more mental burden, such asconst a = 1 if(a === void 0 || a === 1) {}Copy the code
Maintenance and code review costs more than the benefit of saving a few bytes
conclusion
Void 0 is not recommended for scenarios that require compatibility with older browsers (below Internet Explorer 8)
Further reading
Stackoverflow.com/questions/7… Developer.mozilla.org/en-US/docs/… Developer.mozilla.org/en-US/docs/…