Search This Blog

Saturday, October 08, 2011

Javascript: A Better typeof -- Accurately Determine the Type of Variable (Array, String, Boolean, Number, Function, etc.)

If you have ever needed to determine the type of a given Javascript variable, you have probably found the native typeof somewhat inadequate.

Here's a complete solution, adapted from one originally seen on JavaScript Garden:
var realTypeOf = function(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
};

// usage
realTypeOf('hi there'); // String
realTypeOf(true); // Boolean
realTypeOf({}); // Object
realTypeOf([]); // Array
realTypeOf(function() {}); // Function
realTypeOf(new Date()); // Date
realTypeOf(/[0-9]/); // RegExp
realTypeOf($('does-not-exist')); // Null
realTypeOf(document.body); // HTMLBodyElement
realTypeOf($('output-box')); // HTMLDivElement
realTypeOf($$('a')[0]); // HTMLAnchorElement
realTypeOf($$('link')[0]); // HTMLLinkElement
realTypeOf($$('script')[0]); // HTMLScriptElement
realTypeOf(999); // Number
realTypeOf(Math.min(3, 7)); // Number
Try it out in real-time with this JSFiddle example set.

2 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me..I am a regular follower of your blog.
    Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from HTML5 CSS3 Javascript Online Training from India .
    or learn thru HTML5 CSS3 Javascript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. HTML5 CSS3 Javascript Online Training from India


    ReplyDelete
  2. Thanks for writing such great texts.
    Sexy Escort girls

    ReplyDelete