JavaScript Interview Question #166

What is feature detection?

Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced

Quick Interview Answer

Feature detection checks whether the runtime supports a required capability before using it. It is generally more reliable than guessing capabilities from the browser's user-agent string.

Detailed Explanation

Feature detection checks whether the runtime supports a required capability before using it. It is generally more reliable than guessing capabilities from the browser's user-agent string.

Applications can use feature detection to select a fallback, load a polyfill, or disable an optional feature gracefully.

Code Example

if ("IntersectionObserver" in window) {
    const observer =
        new IntersectionObserver(entries => {
            console.log(entries);
        });
} else {
    // Use an appropriate fallback.
}