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.