javascriptundefinedvoid

JavaScript `undefined` vs `void 0`


What exactly is the difference between undefined and void 0 ?

Which is preferred and why?


Solution

  • The difference is that it is sometimes possible to overwrite the value of undefined. However, void anything always returns real undefined (as long as anything finishes evaluating).

    ECMAScript 5 limited this problem by making undefined at global scope read-only (ECMA-262 Ed. 5.1, §15.1.1.3). Nevertheless, undefined remains an ordinary identifier subject to scope lookup and shadowing, so potentially it can still be overridden in a nested scope:

    undefined = 42;
    console.log(0, typeof void 0);      // "undefined"
    console.log(1, typeof undefined);   // "undefined" in ES5 and later
                                     // ("number" earlier)
    
    {
      let undefined = 42;
      console.log(2, typeof void 0);    // "undefined"
      console.log(3, typeof undefined); // "number"
    }
    
    (function (undefined) {
    
    undefined = 42;
    console.log(4, typeof void 0);      // "undefined"
    console.log(5, typeof undefined);   // "number"
    
    })();