When I want to use some relatively new method in JavaScript, let's say history.pushState
, I should check if it is really available before I call it. I found out people are using lot of different methods to check method availability and I used to use my own simple way, which worked for me in every case. Anyway I am still not sure, if my method is completely corrent and widely compatible, because excesive usage of less comfortable way made me think, what is the real reason why people use this instead of simple way.
So I expect answer saying my method is also completely OK, or explaining, in which scenarious my method can fail and so it is not good to use it.
I am using this way:
history.pushState && history.pushState('?attr');
Simply because of early rejection of condition, if pushState is not exists, it will not be called. It works in all ways I tried and without any warning.
Other, less comfortable ways, I found people are using (in IF):
typeof(history.pushState) == 'function'
typeof history.pushState !== 'undefined'
"pushState" in history
typeof(history.pushState) === typeof(Function)
My opinion
In my opinion, in JavaScript is completely fine to check availability of variable or name my if (anythingUndefined) {}
. Of course it can be false negative when variable has 0, false, null etc, but that is not the point of my question, since testing method or object this way always equals to true.