What is feature detection?
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.
Feature detection (recommended)
You directly test if a feature is available:
1// Check if geolocation is supported2if ('geolocation' in navigator) {3 navigator.geolocation.getCurrentPosition(handlePosition);4} else {5 showManualLocationInput();6}78// Check if localStorage is available9if (typeof localStorage !== 'undefined') {10 localStorage.setItem('key', 'value');11}1213// CSS feature detection14if (CSS.supports('display', 'grid')) {15 // use grid layout16}
In CSS, you can use @supports:
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:
1// Bad — just because the browser has documentMode2// does not mean it supports a specific feature3if (document.documentMode) {4 // assume this is IE, assume it supports X5}
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:
1const isChrome = navigator.userAgent.includes('Chrome');23if (isChrome) {4 // assume Chrome supports feature X5}
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.