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.
We can not use the typeof
operator as it returns object
for both arrays and objects in 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.
The quickest and most 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, the toString()
method returns [object Object]
for an object. This is what we want. Now we can be 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 a value 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
An alternate approach is to use the typeof
operator with the Array.isArray()
method to check if a value is an object:
const isObject = obj => {
return typeof obj === 'object' && obj !== null && !Array.isArray(obj)
}
To check if a value is an object, the above isObject()
method does the following:
- Use the
typeof
operator to verify that the variable type isobject
—typeof obj === 'object'
. - Verify the value is not
null
—obj !== null
. - Use the
Array.isArray()
method to verify that the value is not an array —!Array.isArray(obj)
.
The last two steps are necessary to verify a value is an object because the type of null
and an array is also object
.
Read 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.