In an earlier article, we looked at different ways to find out if an object is an array in JavaScript. Today, you'll learn how to check if a variable is an object.

Unfortunately, we can not use the typeof operator as it returns object for both arrays and objects in vanilla JavaScript. This is because the arrays are internally treated as objects in JavaScript:

const fruits = ['Apple', 'Mango', 'Banana'];

const user = {
    name: 'John Doe',
    age: 12
};

typeof fruits; // object

typeof user; // object

Unlike Array.isArray() method which we used for checking if a variable is an array, there is no Object.isObject() method in JavaScript.

So how do we check if something is an object?

The quickest and accurate way to check if a variable is an object is by using the Object.prototype.toString() method.

This method is part of Object's prototype and returns a string representing the object:

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

Object.prototype.toString.call(user); // [object Object]

As you can see above, for objects, the toString() method returns [object Object]. This is precisely what we want. Now we are sure that we are dealing with an object and not an array.

Let us write our own isObject() method by using the above trick to check if an item is a plain object or not:

const isObject = (obj) => {
    return Object.prototype.toString.call(obj) === '[object Object]';
};

isObject([3, 4, 6]);            // false

isObject({});                   // true
isObject({ apple: '🍎' });      // true

isObject('John Doe');           // false
isObject(true);                 // false
isObject(45);                   // false

Take a look at this article to learn more about JavaScript objects, prototypes, and classes.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: