Small keyboard and monitor

Checking if a value is an object in JavaScript or TypeScript

That's a very popular topic in JavaScript programming. Most web developers had such an issue in their work.

Let's imagine a situation. You have some variable that contains a specific value. It may have been passed via function parameters during runtime. And you don't know if that's an object or a simple value. How would you detect that?

There is no simple solution, because of the specifics of the JavaScript language. Although, in some conditions, it's possible to detect if the given value is an object or not. Please keep on reading this guide and you'll see how you can solve that issue in your project.

Checking if value is an object in JavaScript

The most common pattern to detect if the value is an object is using the "typeof" operator. That seems to be very intuitive. You have to compare the result of that operator with the string value of 'object'. If it does equal, then you have an object. See below how it has to be correctly done.

const sampleValue = {};

if (typeof sampleValue === 'object') {
    console.log('Value is an object or null');
}

Now, please try to run the given code in NodeJS. The sample output is shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object or null

However, there is a real issue in the above code. The null value is also an object in JavaScript. That is kept in the language for legacy reasons. Too much code depends on such behavior and changing it may produce some bugs in the code.

That may confuse you a bit, but it's possible to overcome such an issue. You only need to add an additional condition to the if (…) clause in the code. Below, you can see that we also verify that the value is not null.

const sampleValue = {};

if (typeof sampleValue === 'object' && sampleValue !== null) {
    console.log('Value is an object');
}

If we try to run the given code, the output should be like the following.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

There is another case that also has to be discussed here. If you pass the array, the typeof operator will also return the 'object' value. Such a behavior may not be suitable in some cases.

But we can easily fix that issue. To make a code that checks that array is not an object, you may use the Array.isArray() method. It will return true if the passed value contains some array of values. Let's update our sample.

const sampleValue = {};

if (typeof sampleValue === 'object' &&
    sampleValue !== null &&
    !Array.isArray(sampleValue)) {
    console.log('Value is an object and is not an array');
}

The given code should produce output like it's shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object and is not an array

Now, we have a solution that allows you to check if the value is an object. But what if you'd like to reuse that code in your application? In that case, you may create a special function that will contain the given code. This will reduce the amount of duplicated code. Please see our sample below.

const sampleValue = {};

function checkIfObject(value) {
    if (typeof value === 'object' &&
        value !== null &&
        !Array.isArray(value)
    ) {
        return true;
    }

    return false;
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

It's time to test our code. If you try to run it, the console output may be like it's shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Using double exclamation mark to check if the given value is not null

Some web developers prefer to use the double exclamation mark to check if the value is not null. This can produce us a more compact code. However, you have to be careful with this solution, since we are not directly comparing given parameters with the null value.

const sampleValue = null;

function checkIfObject(value) {
    if (typeof value === 'object' &&
        !!value &&
        !Array.isArray(value)
    ) {
        return true;
    }

    return false;
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

If you run the given code, you should see output like it's shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is not an object

Checking if the given value is an object or a function

You may also want to check if the given value is a function. That may be needed if you'd like to make a unified code that tests for various conditions.

The typeof operator should also be used in that case. But it will return the 'function' value if we pass some function.

Now, let's modify our code and see how it works.

const sampleValue = function() {
    return true;
};

function checkIfObjectOrFunction(value) {
    if ((typeof value === 'object' || typeof value === 'function') &&
        value !== null
    ) {
        return true;
    }

    return false;
}

if (checkIfObjectOrFunction(sampleValue) === true) {
    console.log('Value is an object or function');
}

Please run the given code. You should see console output like it's shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object or function

Using the Object class to check if the value is an object

This method is less popular than the others. It's a bit tricky, but still may be used in some conditions. The idea is that we can use a constructor of the Object type to detect if the value is an object or not.

We try to pass some simple values, like numbers or string values. In that case, the constructor will wrap the given data into the new object. However, if we pass the object, then the same object will be returned by that constructor.

After that, we can compare the returned value with the original value. If there is a match, then the value is an object. Otherwise, we have some other simple value there.

The following sample shows how to correctly implement the given method.

const sampleValue = {};

function checkIfObject(value) {
    return (value === Object(value));
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

Now, let's see how it works. If you run the given code, you should see the "Value is an object" message in your terminal.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Using the constructor name to check if the value is an object

That's another interesting method that you can try to use in your code. JavaScript allows us to get the name of the constructor. Then, we may compare that value to the word "Object". If there is a match, then our value contains some object. See the code implementation below.

const sampleValue = {};

function checkIfObject(value) {
    return (value !== null && value.constructor.name === "Object");
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

To ensure that the above code works, let's try to run it in the command line with the help of the NodeJS tool.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Checking if the constructor contains the "Object" value

This is a modification of the previous method. The alternative option is to simply check if the constructor contains the word "Object". For that purpose, we have to convert the constructor to the string. Then, we can call the indexOf() method to check if the desired string is inside of the constructor name. If that word is found, then our value contains some object.

const sampleValue = {};

function checkIfObject(value) {
    return (value.constructor.toString().indexOf("Object") > -1);
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

Let's test our code sample. It can be done as shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Comparing constructor directly to the Object type

There are different methods that can be used to evaluate the constructor. As an example, we can compare it directly to the Object type. If there is a match, then the given value is a JavaScript object. See below how it should be done.

const sampleValue = {};

function checkIfObject(value) {
    return (value?.constructor === Object);
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

Following is the output of the given code sample.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Checking type of the given value

To make a more precise code, we may check the type of the given value. It has to be done with the help of the typeof operator. The returned value must match to the 'object' string. Please see source code below.

const sampleValue = {};

function checkIfObject(value) {
    return (typeof value === 'object' && value?.constructor === Object);
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

It's time to test the given sample. If you run it, the output may be like the following.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Checking if the given value is not empty

You may also check that the given value is not empty. That requires only a small modification to the previous code sample. We need to add a small condition into the checkIfObject() method. See below how it has to be done.

const sampleValue = {};

function checkIfObject(value) {
    return (value && typeof value === 'object' && value?.constructor === Object);
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

You can test the given code with help of the NodeJS application, as shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Using the Object.prototype.toString.call() method

This method is not a standard solution. However, it can produce some acceptable results. We just have to convert the value to a string and evaluate the results. If the output of the call() method equals the '[object Object]' value, then we have some object.

The code implementation is shown below.

const sampleValue = {};

function checkIfObject(value) {
    return (Object.prototype.toString.call(value) === '[object Object]');
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

Now, let's try the given code and see how it works in the Linux terminal.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Using the instanceof operator to check if the value is an object

As you know, JavaScript language has the instanceof operator. It allows us to check if some value was instantiated from the given object.

And this can help us to make a code that can test any value. But there is an important note. We have to check if the passed value is an instance of the standard Object type. See the code sample below.

const sampleValue = {};

function checkIfObject(value) {
    return (value instanceof Object);
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

Following is an example of how the given code can be tested in the command line.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Checking that the given value is not an array

To make the code better, you can combine several conditions together. We may use the typeof operator to check if the given value is an object. Also, if you need, it is worth testing if the passed value is not an array. See how it works in the following code sample.

const sampleValue = {};

function checkIfObject(value) {
    if (typeof value === 'object' &&
        value instanceof Object &&
        !(value instanceof Array)) {
        return true;
    }

    return false;
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

Let's try to run our code and see the console output.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Using the instanceof operator and checking the constructor

There is another interesting option that you may try to use in your project. To make a reliable code, we can add two important conditions. The first one will test if the value is an instance of the Object. And the second can test that the constructor of that value is an Object as well. See the code sample below.

const sampleValue = {};

function checkIfObject(value) {
    return (value instanceof Object && value.constructor === Object);
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

If you run the given code, the console output should be like it's shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Advanced method that allows to checking if value is an object

The following code sample is a combination of the methods that we've described earlier. There you can see a code that performs multiple tests on a value to ensure that it is an object.

You may try to use the given code in your project. However, we strongly recommend testing that method before using it in some critical applications.

const sampleValue = {};

function checkIfObject(value) {
    if (value === undefined || value === null) {
        return false;
    }

    const isInstance = value instanceof Object;
    const isObject = typeof value === 'object';
    const noConstructor = value.constructor === undefined;
    const hasConstructor = value.constructor === Object;

    return ((isInstance || isObject) && (noConstructor || hasConstructor));
}

if (checkIfObject(sampleValue) === true) {
    console.log('Value is an object');
} else {
    console.log('Value is not an object');
}

Now, let's try to use it. We can run our code with help of the NodeJS tool, as shown below.

developer@developer-pc:~/samples/javascript$ node index.js
Value is an object

Conclusion

As you see, the JavaScript language is very complex. There is no simple solution that allows us to easily test if the given value is an object. You have to use various methods that can give you some acceptable result.

It's hard to change such a behavior, because JavaScript has a very long history. Any changes to the language specification must be backward compatible.

Related Articles

Comma separated numbers

Rounding number to at least 2 decimal places in JavaScript or TypeScript

Connected dots and lines

How to return response from an asynchronous call in JavaScript or TypeScript

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *