On many occasions, we would need to check for a JavaScript object’s data type because of its dynamic nature.
In this article, we’ll look at the most accurate way to check for JavaScript object’s type.
Use typeof for Primitive Values
We should use the typeof
for checking primitive values except null
For instance, if we have:
console.log(typeof 1)
console.log(typeof '')
console.log(typeof true)
console.log(typeof 1n)
console.log(typeof undefined)
console.log(typeof Symbol())
We use typeof
to get the type for numbers, booleans, bigints, undefined
, and symbols.
Therefore, we get:
number
string
boolean
bigint
undefined
symbol
from the console log.
Since typeof null
returns 'object'
, we can’t use it to check if an expression returns null
.
Use Object.getPrototypeOf to Get the Prototype of an Object
We can check the prototype of an object with the getPrototypeOf
method.
For instance, if we have:
const o = {}
const proto = Object.getPrototypeOf(o);
console.log(proto === Object.prototype);
Then the console log logs true
since an object literal inherits from Object.prototype
.
We just pass in the object we get the prototype from with the Object.getPrototypeOf
method.
And if we created an object from a constructor, we can do the same check.
For instance, we can write:
const o = new Date()
const proto = Object.getPrototypeOf(o);
console.log(proto === Date.prototype);
to check that o
is created from the Date
constructor.
This should also log true
since o
is created by instantiating Date
.
Conclusion
We should use typeof
to check the type of primitive values.
And we can use the Object.getPrototypeOf
method to check for an object’s prototype.