Getting real object types with JavaScript

Fernando Daciuk
Daily JS Tips
Published in
2 min readJan 6, 2016

If you use typeof to get object type in JavaScript, you’ve probably been through it:

console.log(typeof a); // undefined
console.log(typeof 1); // number
console.log(typeof 'a'); // string
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof new Number(2)); // object

And you thought: “WTF! Everything is an object? What’s the difference?”

In fact, typeof is not the better way to test by object type. What if I tell you that the better way to test it is using a toString() method, would you believe?

I’ll show you:

console.log({}.toString()); // [object Object]

So, you ask me: “How this can help me?”

toString() method of Object returns a string representation of current object. But, how we know, all object methods are treated just like simple functions.

Functions have call() and apply() methods, where we can pass an object as first argument, that represents the “this” inside the object.

Knowing this, we can use something like:

console.log(Object.prototype.toString.call({})); // [object Object]

Nothing changed. But, if we change the “this”, what will happend?

console.log(Object.prototype.toString.call([])); // [object Array]

Nice! Now we have a real type of our objects! And this works with all object types:

console.log(Object.prototype.toString.call('a')); // [object String]
console.log(Object.prototype.toString.call(1)); // [object Number]
console.log(Object.prototype.toString.call(new Number(2))); // [object Number]

Now, we can use something like this:

function is(type, object) {
type = type[0].toUpperCase() + type.slice(1);
var toString = Object.prototype.toString;
return toString.call(object) === '[object ' + type + ']';
}
console.log(is('object', {})); // true
console.log(is('array', [])); // true
console.log(is('object', [])); // false
console.log(is('number', 2)); // true
console.log(is('number', '2')); // false

Very nice, hun?

That’s all, folks! See ya!

--

--