Skip to main content Accessibility Feedback

getType.js

More accurately check the type of a JavaScript object.

Source Code

Examples

let arr = trueTypeOf([]); // array
let obj = trueTypeOf({}); // object
let str = trueTypeOf(''); // string
let date = trueTypeOf(new Date()); // date
let num = trueTypeOf(1); // number
let fn = trueTypeOf(function () {}); // function
let reg = trueTypeOf(/test/i); // regexp
let bool = trueTypeOf(true); // boolean
let nl = trueTypeOf(null); // null
let undef = trueTypeOf(); // undefined

The helper function

/**
 * More accurately check the type of a JavaScript object
 * (c) Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Object} obj The object
 * @return {String}     The object type
 */
function getType (obj) {
	return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

How it works

You may already be familiar with the typeof operator, which returns a string letting you know the type of a JavaScript object.

// returns "number"
typeof 123;

But because most things are objects in JavaScript, it can return some pretty weird results.

typeof []; // object
typeof {}; // object
typeof ''; // string
typeof new Date() // object
typeof 1; // number
typeof function () {}; // function
typeof /test/i; // object
typeof true; // boolean
typeof null; // object
typeof undefined; // undefined

The array, plain object, date, regex, and null all return object. The only really accurate ones are the string, function, boolean, and undefined.

So… how do you accurately check the true type of an object with vanilla JS?

You pass the item that you want to check the type of into the Object.prototype.toString.call() method as an argument. This gets the item’s prototype and converts it to a string, which gives you back something like [object Array] or [object Boolean].

Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [object RegExp]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(); // [object Undefined]

We can then use the String.prototype.slice() method to remove the square brackets ([]) and leading object string.

Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();

Find this useful? You can support my work by purchasing an annual membership.