I need to check the type of a variable in JavaScript. I know 3 ways to do it:
-
instanceof operator:
if(a instanceof Function) -
typeof operator:
if(typeof a=="function" -
toString method (jQuery uses this):
Object.prototype.toString.call(a) == "[object Function]"
Which is the most accurate way to do type checking beetween these solutions? And why? Please don’t tell me that the last solution is better only because jQuery uses that.
[Edit 2023/05/28] See this github repository for a more comprehensive type checker.
How about my home brew function to determine variable ‘type’? It can also determine the type of custom Objects:
Based on the constructor property of variables you could also do:
Now
alert(isType(customObj,SomeObj)returns false. But if SomeObj is a normal Constructor function, it returns true.