Aillyn Aillyn - 8 months ago 45
Javascript Question

Better way to get type of a Javascript variable?

Is there a better way to get the type of a variable in JS than

? It works fine when you do:

> typeof 1
> typeof "hello"

But it's useless when you try:

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

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

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

Is there a better way?

Answer Source

Angus Croll recently wrote an interesting blog post about this -

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

var toType = function(obj) {
  return ({})\s([a-zA-Z]+)/)[1].toLowerCase()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download