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.

10 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
  3. Incredible blog here! It's mind boggling posting with the checked and genuinely accommodating data. Terry Bogard Jacket

    ReplyDelete
  4. I’m really impressed with this valuable blog. Visit Ogen Infosystem best Website Designing and Development Services at best price.
    Best Website Designing Company in Delhi

    ReplyDelete
  5. Hollywood Leather Jackets Sell Best Quality Of Leather Product World Wide Purchase it And Joined Our Team dante coat

    ReplyDelete
  6. This blog was very nicely formatted; it maintained a flow from the first word to the last.
    Dirk Gently Jacket

    ReplyDelete
  7. Thankful for sharing your thoughts. I really like your undertakings and I will hold tight for your further examinations. Everything is unimaginably open with a positive depiction of the challenges. It was really enlightening. Your site is useful. Appreciative for sharing naruto shippuden jacket!

    ReplyDelete
  8. Shop this best Super quality Eternals Jackets SHOP NOW

    ReplyDelete
  9. I like this blog.Thank for sharing this post.yellowstone season 5 jackets

    ReplyDelete
  10. INFORMATIVE POST! I LEARNED A LOT IN A SHORT READ. FOR MORE YOU CAN ALSO GO FOR THE BEST NURSING PADS

    ReplyDelete