1

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) {}
0

2 Answers 2

3

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.

1

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

2
  • A good cavet though, if the prop value could ever be 0 should use in since 0 would return false, though that is the value of the prop.
    – Justin
    Commented Sep 20, 2016 at 23:48
  • Yes, I suppose I'm so used to not writing code this way when specifically looking for a falsey value. The caveat applies conversely to 1 if you still want to reject falsey values that happen to be on the object. For example, 'a' in {a: undefined} => true. There's rarely a one size fits all solution in javascript.
    – Damon
    Commented Sep 20, 2016 at 23:59

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.