Check if a variable is a JavaScript object.

This is a short guide on how to check if a variable or value if an object using JavaScript. In order to do this, we can use the typeof operator, which returns the data type of a given value in a string format.

Take a look at the following JavaScript snippet:

In the example above:

  • We created a simple JavaScript object.
  • We used the typeof operator to check if the variable was equal to “object” and not equal to null.
  • Finally, we printed the result out into the console.

Why do you have to check for null?

You’re probably wondering why I specifically checked to see if the value was null. This is because JavaScript’s typeof operator sees null values as objects.

Take the following example:

If you run the JavaScript snippet above, you will see that the typeof operator returns “object”, despite the fact that the variable in question contains a null value.

Array types.

You should also be aware that the Array type evaluates to “object”. To prevent this, you add an extra check for arrays. Here is a sample of a custom function that I created, which also checks to see if the value is an array:

Hopefully, this guide proved to be useful!

Facebook Comments