What is feature detection?
JavaScriptThe 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:
// Check if geolocation is supportedif ('geolocation' in navigator) { navigator.geolocation.getCurrentPosition(handlePosition);} else { showManualLocationInput();}// Check if localStorage is availableif (typeof localStorage !== 'undefined') { localStorage.setItem('key', 'value');}// CSS feature detectionif (CSS.supports('display', 'grid')) { // use grid layout}In CSS, you can use @supports:
@supports (display: grid) { .container { display: grid; }}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:
// Bad — just because the browser has documentMode// does not mean it supports a specific featureif (document.documentMode) { // assume this is IE, assume it supports X}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:
const isChrome = navigator.userAgent.includes('Chrome');if (isChrome) { // assume Chrome supports feature X}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.