JavaScript Type Tests


/ Published in: JavaScript
Save to your folder(s)

A more useful version of `typeof` and functions to test if a parameter is of a specified type.


Copy this code and paste it in your HTML
  1. /****************************************
  2. A more useful version of `typeof` and functions to test if a parameter is of a specified type.
  3.  
  4. Inspired by http://snipplr.com/view/1996/typeof--a-more-specific-typeof/
  5.  
  6. Examples:
  7.  
  8. var u;
  9. is.Undefined(u) //true
  10. is.Number(u) //false
  11.  
  12. var n=1;
  13. is.Number(n) //true; note that (n instanceof Number) would be false since n is a literal
  14. is.Object(n) //true
  15. /****************************************/
  16.  
  17. var is = new (function(){
  18. var undefined;
  19. function test(type)
  20. {
  21. return function(o){
  22. return (o instanceof type ||
  23. (o !== undefined && !(o instanceof Object) /*i.e., it's a literal*/ && o.constructor === type));
  24. };
  25. }
  26.  
  27. this.Undefined = function(o){ return o === undefined; };
  28. this.Null = function(o){ return o === null; };
  29. this.Boolean = test(Boolean);
  30. this.Number = test(Number);
  31. this.String = test(String);
  32. this.RegExp = function(o){ return (o instanceof RegExp); };
  33. this.Date = function(o){ return (o instanceof Date); };
  34. this.Array = function(o){ return (o instanceof Array); };
  35. this.Function = function(o){ return (o instanceof Function); };
  36. this.Object = function(o){ return (o instanceof Object || this.Boolean(o) || this.Number(o) || this.String(o)); };
  37. })();
  38.  
  39. //note that if argument `o` is an instance of more than one data type (which can happen if you mess with prototypes),
  40. // only the first type tested will be returned
  41. function typeOf(o)
  42. {
  43. for(var type in is){ if(type != "Object" && is[type](o)) return type.toLowerCase(); }
  44. if(is.Object(o)) return "object";
  45. return "";
  46. }
  47.  
  48. /*
  49. //test all data types
  50. //it's worth noting that, in IE, an HTML element is not considered an instance of Object
  51. var u;
  52. function f(){ this.toString=function(){return "[object f]"} };
  53. var h = document.createElement("div");
  54. var a = [u, null, true, (new Boolean), 1, (new Number), "s", (new String), /r/, (new RegExp), (new Date), [0,1], (new Array),
  55. f, function(){}, (new Function), {}, (new Object), (new f), h];
  56. for(var i=0; i<a.length; i++)
  57. {
  58. console.log(a[i]+" : "+typeOf(a[i]));
  59. }
  60. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.