You can do something like this
function typeOf(inputArg) {
if (!arguments.length) {
throw new SyntaxError();
}
if (typeof inputArg === 'undefined') {
return 'undefined';
}
if (inputArg === null) {
return 'null';
}
return ({}.toString.call(inputArg).match(/\[object (Number|Boolean|String|Array|Object|Function)\]/) || ['Object']).pop().toLowerCase();
}
console.log(typeOf(undefined));
console.log(typeOf(null));
console.log(typeOf(1));
console.log(typeOf(true));
console.log(typeOf(''));
console.log(typeOf([]));
console.log(typeOf({}));
console.log(typeOf(function () {}));
console.log(typeOf(/a/));
console.log(typeOf());
Output
undefined
null
number
boolean
string
array
object
function
object
Uncaught SyntaxError
On jsFiddle
However, there are some other bugs in older browsers which can still cause different results. And this does not take into account E4X XML
stuff, or any new types that may get defined in ECMA next
(though probably nothing new). You also need to be aware that this will identify primitive objects, i.e. new String('hello')
as a string
rather than an object
, which may not be what you desire. So you need to think carefully as to your needs or what you are trying to achieve (which I'm not totally clear about).