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

  1. 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
  2. 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

  1. Security assignment

    From the above distinction, it can be seen thatvoid 0To take the place ofundefinedAssignment is actually safer, so almost all scaffolding tools incorporate the ability to convert undefined to void 0
  2. shorter void 0contrastundefinedThe browser transfer process has fewer bytes

So is this the case?

  1. A more secure

    The fundamental reason is that before ECMAScript 5,undefinedAs 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,undefinedSet it to read only, and you don’t have the problems described above, and you don’t have much of an issue with compatibility.

  2. shorter

    Personally think write source code scenarios must be usedvoid 0Instead ofundefinedReading can bring more mental burden, such as
    const 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/…