skip to content

For "can I use X" in JavaScript, how do you choose among feature detection, transpiling and polyfilling, and what can each not do?

level: middleimportance: must knowfreq 38%

answer

  1. syntax or runtime API first
  2. the parser runs before your code
  3. a check supplies nothing
  4. presence is not correct behaviour
  5. some built-ins need the engine

basics

~20 s

First ask whether X is syntax or a runtime API. Syntax must be parsed natively or transpiled; no polyfill or runtime check can supply it. A missing API can be detected at runtime and then polyfilled or worked around.

solid answer

~50 s

I first ask what X is and which runtimes must run it. If X is syntax, like `??` or a private `#field`, an engine that predates it fails while parsing, before any line executes, so a polyfill cannot add it and an `if` or `try` around it cannot save the file. The answer is native support in every target, or transpiling it down. If X is a runtime API, such as `Object.groupBy`, transpiling leaves the call as it is. Then `typeof Object.groupBy === "function"` tells me at runtime whether it exists, and I use a fallback or a polyfill that defines it. Detection provides nothing itself and proves presence, not correct behaviour. A polyfill costs bytes and cannot reproduce what needs engine support, such as `Proxy`. If every target ships X natively, I need none of the three.

code

javascript · 11 lines
javascript
function parses(source) {
  try {
    new Function(source); // compiled here, never called
    return true;
  } catch (err) {
    return false;
  }
}

console.log(parses("return null ?? 1"));  // true on an engine that knows ??
console.log(parses("return null ??? 1")); // false: no engine parses this

go deeper

for a junior

Recall the sorting rule: syntax is transpiled, runtime APIs are polyfilled, and a check at runtime only tells you what exists. Be able to say that syntax cannot be polyfilled.

for a middle

Explain the reason in terms of parse time: an engine rejects the whole script before anything runs, so a guard or a try in that file cannot help. Then show what a detection check does and does not prove.

for a senior

Start from the actual runtime population, because the best answer is often that all targets ship it. Weigh polyfill bytes and global patching against a fallback, and name features that no tool can supply.

for a principal

The tradeoff is the cost of supporting old runtimes: build complexity, shipped bytes and global patches versus lost users. A clear support policy decides most of these answers before anyone asks.

## Two questions come first "Can I use X?" sounds like one question and is really two. 1. **What runs this code?** List the browsers and Node releases, then look up X for those versions. If they all ship it, use it directly and stop here. 2. **What kind of thing is X?** A **syntax** feature is a form the parser has to understand, such as `??`, `??=`, `class` or a private `#field`. A **runtime API** is a value reached at runtime, such as `Object.groupBy` or `Array.prototype.toSorted`. The split matters because of when each is needed. An engine **parses a whole script before executing any of it**. If the parser meets a token it does not know, it raises a `SyntaxError` and nothing in that script runs, including lines above the unknown syntax. A missing API, by contrast, fails only when a line reaches it, with a `TypeError` for a missing method or a `ReferenceError` for a missing global, and earlier lines have already run. ## The three tools **Feature detection** is a runtime check that a capability exists, for example `typeof Object.groupBy === "function"` or `"toSorted" in Array.prototype`. - It works because the check itself is ordinary syntax that every target can parse. - It supplies nothing. You still need a fallback for the branch where the answer is no. - It proves presence, not correct behaviour. A partial or early implementation passes the same check. When behaviour matters, test the behaviour. **Transpiling** is a build step that rewrites newer syntax into older equivalent syntax, using a tool such as Babel. - It handles syntax, so a target engine never sees the form it cannot parse. - It does not make a missing method exist. A call to `items.toSorted()` stays a call to `items.toSorted()`. - It only helps code that passes through it, and the older code it produces runs in place of the original form. Its internals and configuration belong with build tooling. **Polyfilling** is running ordinary script that defines a missing API, usually guarded by a detection check so a native version wins. A library such as core-js collects many of these. - It handles runtime APIs that plain script can express. - It cannot add syntax. Script can define values, but it cannot change what the engine's parser accepts, so the file using the syntax is still rejected. - It costs download and parse time, and it usually edits shared globals, so its semantics must match the standard closely. - It cannot faithfully reproduce everything. `Proxy` intercepts fundamental operations inside the engine, so an older engine cannot be taught that with script. ## Side by side | | Feature detection | Transpiling | Polyfilling | |---|---|---|---| | When it acts | At runtime | At build time | At runtime | | Works for syntax | Only with a string-based probe | Yes | No | | Works for runtime APIs | Yes, reports presence | No | Yes, where script can express it | | Provides the feature | No | Yes, as older syntax | Yes, as script | | Main limit | Proves presence only | Cannot add a missing method | Bytes, and what script cannot do | ## Why a `try` cannot rescue new syntax This snippet looks defensive and is not: ```js try { port = cfg.port ?? 80; } catch (e) { port = 80; } ``` On an engine that predates `??`, the `catch` never gets a chance to run. The failure happens at parse time, before the `try` statement exists as running code. Errors a `try` catches are runtime errors in code that has already parsed. You can test syntax at runtime by putting it in a string, because `new Function(source)` parses that string when it is called and throws a catchable `SyntaxError`. Strict Content Security Policy settings forbid `Function()`, so such a probe fails there whatever the engine supports. The modern code also has to sit in a separate file, loaded only after the probe passes, since a single unknown token in the main file defeats everything. ## Choosing - **Every target ships it:** use it, with none of the three. - **Syntax, and some target lacks it:** transpile, or do not use it. - **API, and some target lacks it:** polyfill it, or detect and fall back, depending on whether the feature is essential or an enhancement. - **Needs the engine, and some target lacks it:** none of the three makes it work. Choose a different design or drop that target.

  • Why does `try { port = cfg.port ?? 80; } catch (e) { port = 80; }` not protect an older browser?
    An engine parses the whole script before running any of it. An engine that predates `??` raises a `SyntaxError` at parse time, so no statement runs, including the `try`, and lines above it. `try` catches runtime errors in code that has already parsed.
  • How can you test for syntax support at runtime, given that an `if` cannot do it?
    Put the syntax in a string: `new Function(source)` parses it when called and throws a catchable `SyntaxError`. Strict Content Security Policy settings forbid `Function()`, so the probe fails there regardless. Code using the syntax must live in a separate file, loaded only after the probe passes.
  • What can neither a transpiler nor a polyfill provide on an older engine?
    Features that need the engine itself. `Proxy` is the usual example: it intercepts fundamental operations such as property reads inside the engine, and script running on an older engine cannot hook those for arbitrary objects. Where such a target must be supported, the design has to avoid the feature.
  • If `typeof X === "function"` is true, can you rely on X?
    You can rely on its presence only. The check says nothing about whether the behaviour matches the standard, and an engine may have shipped a partial or earlier form. When a known behaviour matters, call it with a small input and test the result, then fall back if it fails.

  • You can polyfill ?? by loading a script before the code that uses it.
  • A try/catch around new syntax gives older browsers a working fallback.
  • Transpiling the source alone makes Object.groupBy exist on older engines.
  • If typeof X says function, then X is spec-compliant on this engine.
  • Feature detection adds support for a missing feature.
  • Anything a new edition adds can be made to work on old engines with enough tooling.