I’ve seen many different ways of checking for available properties or methods in javascript.
if(typeof window.somePropOrMethod !== "undefined"){ }
if(window.hasOwnProperty("somePropOrMethod")){ }
if("somePropOrMethod" in window){ }
if(!!window.somePropOrMethod) { }
Which one should I use, and why?
Is it all up to personal preference or are there subtle differences between them?
It depends on the situation, and how stringent you want your test to be.
Doesn’t check that the
somePropOrMethodattribute is defined on the specific object; it only checks it’s in the inheritance chain. Normally this won’t matter; especially when checking onwindow.It does however, specifically check the “somePropOrMethod” attribute is notundefinedChecks the whether the specific object holds the attribute and excludes the inheritance chain from it’s search; but it doesn’t check the
somePropOrMethodisn’t undefined.The same as the first, except it doesn’t check against
undefined; it just checks the object has some member (which could be undefined).This checks the object, and it’s inheritance chain (i.e. #1 and #3 territory), but is only checking for a truthy value;
Of course, what you should be doing is if you want a method, you should check it’s a function;
and you should do the same for other attributes (
string,numberetc, or even use theinstanceofkeyword).