Curriculum Series

What is feature detection?

What is feature detection?

What is feature detection?

JavaScript

The short answer

Feature detection checks if a specific feature exists in the browser before using it. Feature inference assumes that if one feature exists, a related feature also exists. UA string detection reads the browser's user agent string to identify the browser. Feature detection is the only reliable approach — the other two lead to bugs.

You directly test if a feature is available:

JAVASCRIPT
1// Check if geolocation is supported
2if ('geolocation' in navigator) {
3 navigator.geolocation.getCurrentPosition(handlePosition);
4} else {
5 showManualLocationInput();
6}
7
8// Check if localStorage is available
9if (typeof localStorage !== 'undefined') {
10 localStorage.setItem('key', 'value');
11}
12
13// CSS feature detection
14if (CSS.supports('display', 'grid')) {
15 // use grid layout
16}

In CSS, you can use @supports:

JAVASCRIPT
1@supports (display: grid) {
2 .container {
3 display: grid;
4 }
5}

This is reliable because you are testing the actual capability, not guessing.

Feature inference (unreliable)

You assume that if one feature exists, another must too:

JAVASCRIPT
1// Bad — just because the browser has documentMode
2// does not mean it supports a specific feature
3if (document.documentMode) {
4 // assume this is IE, assume it supports X
5}

This is fragile because the assumption can be wrong. Browsers evolve independently — having one feature does not guarantee having another.

UA string detection (fragile)

You read the browser's user agent string to identify the browser:

JAVASCRIPT
1const isChrome = navigator.userAgent.includes('Chrome');
2
3if (isChrome) {
4 // assume Chrome supports feature X
5}

Problems with this approach:

  • UA strings can be faked or changed by the user
  • Many browsers include "Chrome" in their UA string even if they are not Chrome
  • New browser versions may drop or add features, making your check outdated

When to use each

  • Feature detection — always use this. It is the most reliable.
  • Feature inference — avoid. It is based on assumptions.
  • UA string — avoid for feature detection. Only use it for analytics (tracking which browsers visit your site).

Interview Tip

The answer is simple: always use feature detection. Show a quick example with if ('geolocation' in navigator) or @supports in CSS. Then explain why UA string detection is unreliable (can be faked, browsers share UA strings). This is usually a quick question that does not require a long answer.

Why interviewers ask this

This tests if you know how to write code that works across different browsers without making fragile assumptions. Feature detection is a fundamental best practice for cross-browser compatibility.

Finished reading?

Mark this topic as solved to track your progress.