0

If you aren't familiar with the new TypeScript "nullish coalescing operator" (??), it's documented here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined.

I've just used this for the first time in some code, and I noticed something odd about the way the operator is translated into JavaScript. Using the TypeScript Playground, you can see that this code:

const message: string = process.env.FOO ?? 'bar';

Is translated into this:

"use strict";
var _a;
const message = (_a = process.env.FOO, (_a !== null && _a !== void 0 ? _a : 'bar'));

Since ?? tests for null or undefined values, why compare to void 0 instead of undefined? I can't think of anything other than perhaps void 0 is just a few characters shorter than undefined. Is there a better reason than that?

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • Does this answer your question? [Should I use \`void 0\` or \`undefined\` in JavaScript](https://stackoverflow.com/questions/19369023/should-i-use-void-0-or-undefined-in-javascript) – mdexp Jan 02 '20 at 02:10
  • @mdexp, that seems to make sense. I haven't had to worry about JavaScript so ancient that `undefined` could change value, but I guess TypeScript is by default trying to translate to the oldest version of JavaScript possible when it can. – kshetline Jan 02 '20 at 02:14
  • typescript is a Microsoft invention, so, of course it translates to code that can be run on ancient browsers :p that's all MicroSoft have ... ancient browsers :p – Jaromanda X Jan 02 '20 at 02:22
  • @Jaromanda X, – kshetline Jan 02 '20 at 02:34

0 Answers0