Why does the TypeScript compiler compile its optional chaining and null-coalescing operators, ?.
and ??
, to
// x?.y
x === null || x === void 0 ? void 0 : x.y;
// x ?? y
x !== null && x !== void 0 ? x : y
instead of
// x?.y
x == null ? void 0 : x.y
// x ?? y
x != null ? x : y
?
Odds are that behind the scenes == null
does the same two checks, but even for the sake of code length, it seems like single check would be cleaner. It adds many fewer parentheses when using a string of optional chaining, too.
Incidentally, I'm also surprised that optional chaining doesn't compile to
x == null ? x : x.y
to preserve null
vs undefined
. This has since been answered: Why does JavaScript's optional chaining to use undefined instead of preserving null?
null
... it always producesundefined
when the thing being referenced is nullish. The reason I'm putting this in a comment and not my answer below is that this really is a separate question and belongs in its own post. – Bewilderment