Java Reference
In-Depth Information
Feature detection is the process of determining if a browser supports a given feature, and it is the
preferred method of browser detection. It requires little maintenance, and it is used to execute code
across all browsers that implement (or don't implement) a specific feature.
For example, all modern browsers support navigator.geolocation . You can use it in your page,
and visitors using those browsers will not experience any issues. However, visitors using Internet
Explorer 8 would experience script errors because IE8 does not support geolocation.
This is a common problem because even the latest versions of browsers don't always support the same
features, but you can avoid these types of issues with feature detection. The pattern is simple: Check if
the feature exists, and only use the feature if it does. Therefore, all you need is an if statement, like this:
if (navigator.geolocation) {
// use geolocation
}
Whoa! Wait a minute! This code uses navigator.geolocation as the if statement's condition! Isn't
the if statement supposed to work on true or false values? Yes, but JavaScript can treat any value
as true or false . We call these truthy and falsey . They aren't true boolean values, but they evaluate
to true and false when used in a conditional statement.
Here's how this works; the following values are falsey:
0
"" (an empty string)
null
undefined
[] (an empty array)
false
Just about everything else is truthy.
In browsers that don't support geolocation, navigator.geolocation is undefined and is therefore falsey.
We know that this can be confusing, and it can add some ambiguity to your code. So many
JavaScript developers like to avoid using truthy/falsey statements, and opt for a clearer
comparison by using the typeof operator, like this:
if (typeof navigator.geolocation != "undefined") {
// use geolocation
}
The typeof operator returns a string that tells you the type of a value or object. In this code, the
typeof operator is used on navigator.geolocation . In browsers that support geolocation, the type
is "object" ; in browsers that don't, it's "undefined" .
You can use the typeof operator on any object or value. Refer to the following table for the possible
values returned by typeof :
Search WWH ::




Custom Search