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, -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.

No comments:

Post a Comment