I saw this piece of code in jQuery’s source. I am a novice in javascript and I would like to know how this works.
if ( "getBoundingClientRect" in document.documentElement ) {
// do something...
}
How is it different from
if(document.documentElement.getBoundingClientRect) {
// do something...
}
…?
That’s an expression using the
inoperator. Theinoperator checks to see if the target object has a property with the given name (directly, or via the object’s prototype).What it’s doing is seeing if
document.documentElementhas a property with the namegetBoundingClientRect(which is a handy function jQuery would like to use if the browser provides it).indoesn’t require fetching the value of the property, just checking that it exists. Also note that the second form you list would test the truthiness of the value of the property. In the case of a function likegetBoundingClientRectthat would be fine, but if you wanted to test something whose value might come back falsey (0,"", etc.), it would fail even though the property exists.You’ll see this sort of thing a lot when doing feature-detection. For instance, if you want to know if a browser supports the HTML5
placeholderattribute:This is an example where we couldn’t use the form
if (document.createElement('input').placeholder)because if the condition were false, we wouldn’t know whether it was false because the property didn’t exist, or false because the property existed but had a falsey value (and the default value forplaceholderis"", which is indeed falsey).Gratuitous link to list of feature detections.