Search code examples
javascriptreactjsnull-coalescing-operator

JavaScript: understanding void 0 in ?? operator polyfill


I was curious whether null coalescing operator ?? had a polyfill in default create-react-app setup. It turns out it does:

const App = () => {
    const foo = 'custom value';

    return (
        <div>
            {foo ?? 'default value'}
        </div>
    );
};

Becomes:

const App = () => {
  const foo = 'custom value';
  return /*#__PURE__*/Object(react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__["jsxDEV"])("div", {
    children: foo !== null && foo !== void 0 ? foo : 'default value'
  }, void 0, false, {
    fileName: _jsxFileName,
    lineNumber: 7,
    columnNumber: 9
  }, undefined);
};

The most interesting part is the foo !== null && foo !== void 0 ? foo : 'default value', which is the polyfill for the ?? operator. While foo !== null is obvious, I don't quite get the foo !== void 0 part. What does it mean?

I checked and void 0 === undefined is true, but why isn't it simply foo !== undefined?


Solution

  • void 0 is the same thing as undefined, most of the time. There are two benefits to using void 0:

    • It's shorter (which can be useful for minifiers)

    • The identifier undefined can be created when not on the top level, leading to unexpected behavior:

    (() => {
      const undefined = 'foo';
    
      // later in the code:
    
      const actuallyUndef = (() => {})();
      console.log(actuallyUndef === undefined);
    })();

    That's an extremely pathological case, but using void 0 is a tiny bit safer.

    Ancient browsers used to permit the creation of undefined on the top level as well, but this is luckily no longer permitted.