How to reliably detect the object type of a JavaScript variable?

Published: | Updated: | by Julian Knight Reading time ~1 min.
📖 Kb | 📎 Development | 🔖 JavaScript, ECMAscript

The nature of JavaScript means that everything is treated as an object (sort of). It can be remarkably hard to reliably detect what type of object something is and there isn’t a single function in JavaScript that can be used in all cases. So how do we do it? Here are some options

The “official” way is to use Object.prototype.toString.call(objectToTest). This will work no matter what the object is, even null or undefined. However, it is relatively quite slow.

A quicker way is probably to use objectToTest.__proto__.constructor.name. However, note that this will fail (as do many other methods) if the object is null or undefined.

Simple function 🔗︎

This simple function provides an easy to use way to return the object type and a list of simple type ENUM’s to compare against.

Note that using Object.prototype.toString.call(prop) is a fairly slow operation and therefore this should be avoided when maximum performance is required.

var types = {
   'get': function(prop) {
      return Object.prototype.toString.call(prop)
   },
   'null': '[object Null]',
   'object': '[object Object]',
   'array': '[object Array]',
   'string': '[object String]',
   'boolean': '[object Boolean]',
   'number': '[object Number]',
   'date': '[object Date]',
}

Used as:

if(types.get(prop) == types.number) {
    // ...
}

It can, of course, be extended with your own bespoke object types.

This is taken from an answer to the StackOverflow Question: The most accurate way to check JS object’s type?.


comments powered by Disqus