skip navigation



About Us

Fixing the Javascript `typeof` Operator

10/31/2013, 3:00pm CDT
By Jesse Houchins

Learn how to get the results you expect without jumping through hoops.

In javascript, the typeof operator can be used to determine the kind of variable you are dealing with. Here is a simple example:

console.log(typeof {})     // => 'object'


Now I can write code that is type aware... NOT SO FAST. As those with some experience writing javascript will soon point out, the following is also true:

console.log(typeof [1,2,3])   // => 'object'
console.log(typeof null)      // => 'object'

What! Why?

Because everything in javascript is an object. Sure, strings, numbers and functions know their true type, but everything else is suffering from severe identity crisis.

Am I Screwed, Then?

Some would say, since you're writing javascript, that this is a rhetorical question, but there is hope. The instanceof operator is more reliable when checking object types, but it has issues when dealing with objects created in different DOM frames.

The Fix.

I prefer the following method, based on a concept I ran across while searching the Googles:

function realTypeof(x){
 if (typeof x === 'object') return^\[object |\]$/g,'').toLowerCase()
 return typeof x

This does what typeof should do (in my opinion) and will return things like:

realTypeof(undefined)       // => 'undefined'
realTypeof(null)            // => 'null'
realTypeof(new Function())  // => 'function'
realTypeof({})              // => 'object'
realTypeof([])              // => 'array'
realTypeof(new Date())      // => 'date'
realTypeof('')              // => 'string'
realTypeof(7)               // => 'number'
realTypeof(NaN)             // => 'number'

Depending on your preference, you may want NaN or Invalid Date objects to return as such, which will require additional logic. However, for most cases, this will do the trick.

Tag(s): Home  Javascript