Finding Variable Type in JavaScript
typeof is only good for returning the "primitive" types such as number, boolean, object, string and symbols. You can also use instanceof
to test if an object is of a specific type.
function MyObj(prop) {
this.prop = prop;
}
var obj = new MyObj(10);
console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
Use typeof
:
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
So you can do:
if(typeof bar === 'number') {
//whatever
}
Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):
> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"
The type of an array is still object
. Here you really need the instanceof
operator.
Update:
Another interesting way is to examine the output of Object.prototype.toString
:
> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"
With that you would not have to distinguish between primitive values and objects.