A better JavaScript typeof function


Often times during our JavaScript development we may need to know the type of an "object" in JavaScript, using the typeof functionality provided by JavaScript works sometimes and other times it might fail. Some examples are provided below.


typeof 2              : returns "number"
typeof ""           : returns "string"
typeof function(){}   : returns "function"
typeof /\d/                 : returns "object"                     // fail !!! this is actually a regexp


I have a written a simple replacement function for typeof that pretty much returns the same results, but it's more robust and always returns the correct value

var itypeof = function (val) {
    return Object.prototype.toString.call(val).replace(/(\[|object|\s|\])/g,"").toLowerCase()
}


itypeof(2)                         : returns "number"
itypeof ("")                       : returns "string"
itypeof (function(){})         : returns "function"
itypeof (/\d/)                     : returns "regexp"


Comments


  1. nice article.thank you for sharing useful post.
    web programming tutorial
    welookups

    ReplyDelete

Post a Comment

Popular posts from this blog

JavaScript Module Pattern: 2 Forms

Pseudo-Random UUID Generation with mask support

Mocking Ajax with the JQuery Mockjax Library