More JavaScript Questions 101(MJSQ 101):
Continuing from my original blog post, I give you more javascript 101 questions answered!:
Question this week:
What's the difference between feature detection, feature inference, and using the UA string?
Feature Detection
Feature detection is discovering if a browser supports a certain block of code by running tests and running different code depending on if it does or does not. This allows for the browser to always provide a working experience instead of crashing or rendering errors giving a bad user experience.
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
// show the location on a map, perhaps using the Google Maps API
});
} else {
// Give the user a choice of static maps instead perhaps
}
Modernizr is a great library to handle feature detection.
Feature Inference
Feature inference is similar to feature detection, but instead uses another function because it assumes it will also exist:
if (document.getElementsByTagName) {
element = document.getElementById(id);
}
This is not really recommended. Feature detection is more foolproof.
UA String
This is a browser-reported string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. It can be accessed via navigator.userAgent. However, the string is tricky to parse and can be spoofed. For example, Chrome reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string. Avoid this method.
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
}
That's all for today, please leave any comments/questions/corrections in the comments. Thanks!
Sources:
Huge huge thanks to github user: yangshun for aggregating the most popular JS, CSS and HTML questions and giving us his answers to it. My weekly blog posts are to go over several questions at a time to reinforce my knowledge of fundamental javascript as I grow my expertise in it. Many of my blog will be paraphrasing if not direct quotes from his github. Find his tech interview handbook here and please support him!
And an additional thank you to Flatiron alum: Marissa O. who is a badass developer at Forbes magazine for directing me to his blog!
Top comments (0)