I am Hack Sparrow
Captain of the Internets.

JavaScript – Check Object Types

There are times when you want to know the object type of an instance in JavaScript, whether it is an Array, or a Function, or an Object, a String etc. There are two flavors to doing that, one involves the use of the instanceof operator, the other involves stringification of the object's prototype. Follow the examples below, I show both the techniques.

First create these variables:

var a = [];
var o = {};
var s = '';
var n = 42;
var f = function() {};

Check if object is an Array

if (a instanceof Array) console.log('Array!');
if (Object.prototype.toString.call(a) === '[object Array]') console.log('Array!');

Check if object is an Object

if (o instanceof Object) console.log('Object!');
if (Object.prototype.toString.call(o) === '[object Object]') console.log('Object!');

Check if object is a String

if (s instanceof String) console.log('String!');
if (Object.prototype.toString.call(s) === '[object String]') console.log('String!');

Check if object is a Number

if (n instanceof Number) console.log('Number!');
if (Object.prototype.toString.call(n) === '[object Number]') console.log('Number!');

Check if object is a Function

if (f instanceof Function) console.log('Function!');
if (Object.prototype.toString.call(f) === '[object Function]') console.log('Function!');

That's how you check object types in JavaScript. Any queries, need more examples, ping me in the comments.

3 Responses to “JavaScript – Check Object Types”

  1. ivoszz says:

    Is it something wrong to use just typeof x, if it is enough to know only the difference function/number/string/object?

  2. Captain says:

    @ivoszz, nothing wrong technically. But I would recommend getting into the habit of using instanceof so that typeof a doesn’t throw you off guard in future.

  3. ivoszz says:

    @captain: Thanks.

Make a Comment