RealTypeOf: a better JavaScript typeof

September 2008

I wish I'd written these ten lines of code a decade ago, trust me I do.

As you no-doubt know, JavaScript has a built-in function called typeof. As the name suggests, it tells you what the type of a particular variable is. For example, calling typeof 1 will tell you 1 is a number, typeof "hello" will tell you "hello" is a string and so on. The problem is, it doesn't differentiate between objects, arrays and dates because technically they are just types of object. JavaScript's typeof works, but it isn't always helpful.

Below is a little function I've written which tells you exactly what type of variable you're dealing with. It won't save the planet, but it could have saved some of my hair.

function RealTypeOf(v) {
  if (typeof(v) == "object") {
    if (v === null) return "null";
    if (v.constructor == (new Array).constructor) return "array";
    if (v.constructor == (new Date).constructor) return "date";
    if (v.constructor == (new RegExp).constructor) return "regex";
    return "object";
  }
  return typeof(v);
}

If you're interested in learning more about this kind of stuff I suggest you pay a visit to Douglas Crockford's website, or better still, buy his excellent JavaScript book. To see other JavaScript work I've done, check out my JAWStats web analytics project.

Jon Combe