4

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?

Robo Robok
  • 21,132
  • 17
  • 68
  • 126

1 Answers1

5

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • See, I didn't know that you can overwrite `undefined` inside a function! I thought that modern browsers just don't allow it, but you are right! Overwriting `undefined` inside a function actually works, even in strict mode. – Robo Robok Feb 14 '21 at 16:33