Search code examples
javascriptuser-agentbrowser-feature-detection

What's the difference between feature detection, feature inference, and using the UA string


I was asked this question in a job interview recently, specifically around Javascript. I was wondering the proper response.

What exactly is the difference between feature detection, feature inference, and using the User agent string?


Solution

  • Feature detection checks a feature for existence, e.g.:

    if (window.XMLHttpRequest) {
        new XMLHttpRequest();
    }
    

    Feature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.:

    if (document.getElementsByTagName) {
        element = document.getElementById(id);
    }
    

    Checking the UA string is an old practice and should not be used anymore. You keep changing the UA checks and never benefit from newly implemented features, e.g.:

    if (navigator.userAgent.indexOf("MSIE 7") > -1){
        //do something
    }