Reputation: 45400
What is the most standards and best browser compatibility for checking if a given property of an object exists in JavaScript?
I can think of the following:
1.
if(window && 'navigator' in window && 'userAgent' in window.navigator) {}
2.
if(window && window.navigator && window.navigator.userAgent) {}
Upvotes: 1
Views: 1266
Reputation: 3713
The window &&
check at the start of each of the checks is unnecessary. There's never a natural case where that will evaluate to false. (If you run the code in Nodejs or in a web worker where the window
global isn't present, then the line will throw an exception, and not evaluate to false. There's no environment where window &&
will improve things, and having that there is misleading.)
#1 will check whether the window
object has a navigator
property with any value, etc. #2 will check whether the window
object has a navigator
property with a truthy value. Unless you expect window.navigator
or window.navigator.userAgent
to be present as properties but be set to false
, null
, undefined
, 0
, NaN
, or ''
(which those specific properties aren't ever naturally in browsers), then #2 will work just fine and it's nicely shorter.
Upvotes: 3
Reputation: 4346
Both are completely standard and fully supported. Go with 2
because it is the most commonly used, is shorter, and (not that it matters) was supported since the inception of javascript, whereas 1
came along in ES3.
See MDN for more details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Upvotes: 1