JavaScript instanceof Operator
By Flavio Copes
Learn how the JavaScript instanceof operator checks if an object is an instance of a class, including parent classes it inherits from in the prototype chain.
The JavaScript instanceof operator returns true if the first operand is an instance of the object passed on the right, or one of its ancestors in its prototype chain.
In this example you can see that the myCar object, of class Fiesta, responds true to instanceof Fiesta, and also responds true to instanceof Car, because Fiesta extends Car:
class Car {}
class Fiesta extends Car {}
const myCar = new Fiesta()
myCar instanceof Fiesta //true
myCar instanceof Car //true
How does it work under the hood?
instanceof walks the prototype chain of the object. It checks whether the prototype property of the constructor appears anywhere in that chain.
That explains the myCar instanceof Car result above. Fiesta extends Car, so Car.prototype sits in the chain of every Fiesta instance.
It also explains why almost everything responds true to instanceof Object:
const numbers = [4, 8, 15]
numbers instanceof Array //true
numbers instanceof Object //true
Arrays inherit from Object, so both checks pass.
When would you use it?
A practical case is telling error types apart in a catch block:
try {
JSON.parse(input)
} catch (err) {
if (err instanceof SyntaxError) {
console.log('invalid JSON')
} else {
throw err
}
}
JSON.parse() throws a SyntaxError on malformed input. The check lets us handle that specific case, and re-throw anything unexpected.
It’s also useful with your own class hierarchies, when a function accepts different kinds of objects and needs to branch on the concrete type it received.
Watch out for primitives
instanceof only works with objects. Primitive values always return false, even when a matching wrapper class exists:
'hello' instanceof String //false
42 instanceof Number //false
A string literal is a primitive, not a String object, so the check fails. The fix is using typeof for primitives:
typeof 'hello' //'string'
typeof 42 //'number'
My rule: typeof for primitives, instanceof for objects and class instances.
One last note on arrays. Prefer Array.isArray() over instanceof Array, because it also works with arrays created in another frame or realm, where instanceof Array returns false.
Related posts about js: