Sub topic 13
Browser, Node.js and Transpiler Support
This chapter assumes you already know how ?., ?? and ??= behave, which earlier chapters covered. It also assumes you have used a build tool such as Babel, TypeScript or esbuild and know what a package.json is. The question here is practical: will your code run where you deploy it? If it won't, how do you make it run without changing what it means?
Which ECMAScript Version Added Each Operator
ECMAScript is the specification that defines JavaScript, and it gets a new edition each year. Engines add features separately, so the edition alone doesn't tell you whether a particular browser supports a feature. It does tell you which "target" setting your tools need.
| Operator | Name | ECMAScript edition |
|---|---|---|
| `?.`, `?.[]`, `?.()` | Optional chaining | ES2020 (ES11) |
| `??` | Nullish coalescing | ES2020 (ES11) |
| `??=` | Nullish coalescing assignment | ES2021 (ES12) |
The edition gap matters. Some environments support ?. and ?? but not ??=. It's easy to assume all three always arrive together, and that assumption is a common source of build surprises.
Native Runtime Support
These are the first versions that run each operator without flags or transpilation:
| Runtime | `?.` | `??` | `??=` |
|---|---|---|---|
| Chrome / Edge (Chromium) | 80 | 80 | 85 |
| Firefox | 74 | 72 | 79 |
| Safari (macOS and iOS) | 13.1 | 13.1 | 14 |
| Opera | 67 | 67 | 71 |
| Node.js | 14.0 | 14.0 | 15.0 |
| Deno | 1.0 | 1.0 | 1.0 |
Every evergreen browser has supported all three operators since late 2020. Your actual risks come from three places:
- Old Node.js versions. Node 12 reached end of life in 2022, but you can still find it in old CI images, AWS Lambda layers and corporate servers. On Node 12, any file containing
?.fails to load. - Pinned or embedded browsers. Kiosk devices, smart TVs, older iOS devices that can't upgrade past Safari 13, and embedded WebViews in some apps can lag years behind.
- Tools, not runtimes. Older parsers inside bundlers, linters and test runners can reject the syntax even when the runtime would accept it.
Detecting Support at Runtime
You can't write if (supportsOptionalChaining) { a?.b } because the engine parses the whole file before running any of it. To detect syntax support, compile a string at runtime and catch the error:
function supportsSyntax(source) {
try {
new Function(source);
return true;
} catch (err) {
return false;
}
}
console.log("optional chaining:", supportsSyntax("return null?.x"));
console.log("nullish coalescing:", supportsSyntax("return null ?? 1"));
console.log("nullish assignment:", supportsSyntax("let a = null; a ??= 1; return a"));On any current runtime, all three lines print true. Two limits apply. First, a Content Security Policy without 'unsafe-eval' blocks new Function, so the check reports false everywhere. Second, detecting support only helps if you also have a fallback bundle to load. In practice, most teams compile to a known target at build time and skip runtime detection.
How Transpilers Rewrite the Operators
A transpiler rewrites newer syntax into older syntax that means the same thing. Knowing what the output looks like helps when you debug compiled code or read stack traces.
Optional chaining
obj?.a.b becomes a strict check against null and undefined:
const obj = { a: { b: 42 } };
let _obj;
// Equivalent of: obj?.a.b
const result =
(_obj = obj) === null || _obj === void 0 ? void 0 : _obj.a.b;
console.log(result); // 42A few details are worth noticing:
- The temporary variable
_objmakes sureobjis evaluated only once. If the left side were a function call such asgetUser()?.name, a naive rewrite would callgetUser()twice. void 0always producesundefined. Old code used it becauseundefinedcould be reassigned in ES3 engines.- The rest of the chain,
.a.b, sits inside the false branch. That's how short-circuiting is preserved: ifobjis nullish, nothing after it runs.
Optional calls keep `this`
A method call has to keep its receiver. obj.method?.() can't become a plain fn() call, because this would be lost. Transpilers use .call:
const counter = {
count: 0,
increment() {
this.count += 1;
return this.count;
},
};
let _counter$increment;
// Equivalent of: counter.increment?.()
const value =
(_counter$increment = counter.increment) === null ||
_counter$increment === void 0
? void 0
: _counter$increment.call(counter);
console.log(value); // 1Nullish coalescing and assignment
a ?? b becomes a conditional, and a ??= b becomes a guarded assignment:
const settings = { volume: 0 };
let _settings$volume;
// Equivalent of: settings.volume ?? 50
const volume =
(_settings$volume = settings.volume) !== null &&
_settings$volume !== void 0
? _settings$volume
: 50;
// Equivalent of: settings.theme ??= "dark"
settings.theme !== null && settings.theme !== void 0
? settings.theme
: (settings.theme = "dark");
console.log(volume); // 0
console.log(settings.theme); // "dark"The assignment only runs in the nullish branch. This matches the native rule that ??= doesn't write to the property when a value is already present, which matters for setters and frozen objects.
The `document.all` edge case
You may wonder why transpilers write x === null || x === void 0 and not the shorter x == null. The reason is document.all, a legacy browser object with special behavior: it's falsy, and document.all == null is true. However, it's neither null nor undefined, so the spec says document.all ?? "fallback" returns document.all. The strict checks follow the spec exactly. Babel offers an assumption named noDocumentAll that switches to != null for smaller output. You can enable it safely as long as your code never passes document.all through these operators, and almost no modern code does.
Configuring Your Tools
Babel
@babel/preset-env includes the transforms (@babel/plugin-transform-optional-chaining, @babel/plugin-transform-nullish-coalescing-operator and @babel/plugin-transform-logical-assignment-operators). It applies them only when your targets need them:
{
"presets": [
["@babel/preset-env", { "targets": "> 0.5%, last 2 versions, not dead" }]
],
"assumptions": {
"noDocumentAll": true
}
}If your targets all support ES2021, Babel leaves the operators untouched. Older documentation names the plugins @babel/plugin-proposal-*. Those packages are deprecated, and the transform names replace them.
TypeScript
TypeScript understands ?. and ?? from version 3.7 and ??= from version 4.0. The target option in tsconfig.json decides whether it rewrites them:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true
}
}With "target": "ES2020", TypeScript leaves ?. and ?? alone but still rewrites ??=, because ??= is an ES2021 feature. With "target": "ES2019" or lower, it rewrites all three.
esbuild and other bundlers
esbuild takes a --target flag that accepts ECMAScript editions or specific engines:
npx esbuild src/index.js --bundle --target=es2019,safari13 --outfile=dist/index.jsVite and Rollup setups usually pass a similar target through to esbuild or Babel. One historical gotcha: webpack 4's parser (Acorn 6) can't parse ?. at all. The build fails with "Module parse failed: Unexpected token" even if Babel runs on your own source, because dependencies in node_modules often skip Babel. To fix it, upgrade to webpack 5 or run Babel on those dependencies too.
Linters and test runners
ESLint parses code using its ecmaVersion setting. If that is set below 2020, ?. is a parse error, and below 2021 ??= is a parse error. Flat config defaults to "latest", but older .eslintrc files often pin a lower value. Jest uses Babel through babel-jest, so it follows your Babel targets. When Jest runs on old Node with targets aimed at that Node version, it transpiles the operators, which can make a test pass locally while production code that skipped Babel fails.
Shipping Libraries
If you publish a package to npm, the people who install it decide whether node_modules gets transpiled, not you. Many projects skip transpiling dependencies for build speed. If your package ships raw ??= and someone installs it into a project that targets Node 14, it fails at load time with a SyntaxError that points into your package. You have three options:
- Compile your published output to a conservative target, such as ES2019.
- Ship modern syntax, and declare it in
"engines": { "node": ">=15" }and in your README. - Publish both builds through
exportsconditions.
Option 2 is common today and reasonable, as long as you state the requirement.
Exercises
Exercise
Your tsconfig.json sets "target": "ES2020". Which of ?., ?? and ??= will TypeScript rewrite in the output, and why?
Show answer
Only ??=. Optional chaining and nullish coalescing are ES2020 features, so an ES2020 target can keep them as is. Nullish coalescing assignment is an ES2021 feature, so TypeScript rewrites it into a guarded assignment.
Exercise
A page loads one script. Line 400 uses user?.name inside a function that is never called. On Safari 13.0, does the code on line 1 run?
Show answer
No. Safari 13.0 doesn't support optional chaining (support arrived in 13.1). The whole script fails to parse before anything runs, so no line executes, whether or not that function is ever called.
Exercise
Why does transpiled output for getUser()?.name store getUser() in a temporary variable, and what bug would a rewrite like getUser() == null ? undefined : getUser().name cause?
Show answer
The temporary variable makes sure getUser() is evaluated once, as in the native operator. The naive rewrite calls getUser() twice. That repeats any side effects, such as network calls or counters, and it can return a different value the second time.
Exercise
Babel's noDocumentAll assumption makes x ?? y compile to x != null ? x : y. For which value does this give a different result than the spec, and what does each version return?
Show answer
document.all. Under the spec, document.all ?? y returns document.all, because it is neither null nor undefined. With the loose check, document.all != null is false, so the compiled code returns y.