Justin Justin - 2 months ago 19
Javascript Question

Checking if property exists in object in JavaScript (browser compliance)

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

Answer

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.

Comments