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:
//An example object. var example = {param: true}; //Check to see if variable is an object using the //typeof operator if(typeof example === 'object' && example !== null){ console.log('Variable is an object!'); } else{ console.log('Variable is not an object!'); }
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:
//A variable that has been set to null. var test = null; //The typeof operator will return "object" console.log(typeof test);
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:
function isObject(val){ if(typeof val === 'object' && val !== null && !Array.isArray(val)){ return true; } return false; }
Hopefully, this guide proved to be useful!