Better way to get type of a Javascript variable?

Aillyn picture Aillyn · Sep 12, 2011 · Viewed 352.5k times · Source

Is there a better way to get the type of a variable in JS than typeof? It works fine when you do:

> typeof 1
"number"
> typeof "hello"
"string"

But it's useless when you try:

> typeof [1,2]
"object"
>r = new RegExp(/./)
/./
> typeof r
"function"

I know of instanceof, but this requires you to know the type beforehand.

> [1,2] instanceof Array
true
> r instanceof RegExp
true

Is there a better way?

Answer

ipr101 picture ipr101 · Sep 12, 2011

Angus Croll recently wrote an interesting blog post about this -

http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

He goes through the pros and cons of the various methods then defines a new method 'toType' -

var toType = function(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}