Skip to main content Accessibility Feedback

True type checking with vanilla js

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

var num = 123;

// Returns "number"
typeof num;

Because everything is an object in JavaScript, it can return some pretty weird results. Here’s a set of examples from my buddy Todd Motto.

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?

A workaround

Todd provides a neat solution, too.;

You pass the thing you want to check the type of into call() as an argument. The gets its prototype and converts it to a string, which gives you back something like [object Array] or [object Boolean].[]); // [object Array]{}); // [object Object]''); // [object String] Date()); // [object Date]; // [object Number] () {}); // [object Function]; // [object RegExp]; // [object Boolean]; // [object Null]; // [object Undefined]

A helper function

That’s kind of verbose, though. Here’s a helper function that will return a lowercase string of just the type, without the leading [object or trailing ].

var trueTypeOf = function (obj) {
	return, -1).toLowerCase();

// Returns "array"

// Returns "date"
trueTypeOf(new Date());

I’ve added this on the Vanilla JS Toolkit.

I refer to Todd’s original article on this so often, I thought it would be use documenting here, too.