skip navigation

Here you will find ideas and code straight from the Software Development Team at SportsEngine. Our focus is on building great software products for the world of youth and amateur sports. We are fortunate to be able to combine our love of sports with our passion for writing code.

The SportsEngine application originated in 2006 as a single Ruby on Rails 1.2 application. Today the SportsEngine Platform is composed of more than 20 applications built on Rails and Node.js, forming a service oriented architecture that is poised to scale for the future.

About Us
Home

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'

Wonderful!

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.prototype.toString.call(x).replace(/^\[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