instanceof
Checks whether an object was created by a given class, or by a class that inherits from it.
- Returns
trueorfalse.
Example
#class Exercise {}
class Quiz extends Exercise {}
const quiz = new Quiz()
console.log(quiz instanceof Quiz)
console.log(quiz instanceof Exercise)
console.log(quiz instanceof Object)
console.log(new Exercise() instanceof Quiz)Definition and usage
#The instanceof operator returns true if the given class’s prototype is found in the object’s prototype chain. In practice, it answers the question of whether an object is an instance of that class or one of its derived classes.
It’s most often used to recognize the kind of error in a catch block (error instanceof TypeError) and to tell apart objects of different classes inside one function. Because it accounts for inheritance, an instance of Quiz extends Exercise is at the same time an instance of Exercise and of Object.
For primitive values, such as strings and numbers, the result is always false, because they aren’t objects. Use typeof for those, and Array.isArray() for arrays, which is more reliable. instanceof can also fail for objects coming from another window, such as an iframe, which has its own built-in classes.
Syntax
#object instanceof ConstructorParameters
#object
any value
The value being checked.Constructor
class or function
The class you’re comparing against. If it isn’t a function, the operator throws aTypeError.
More examples
#class NoFuelError extends Error {}
function startLesson(fuel) {
if (fuel <= 0) throw new NoFuelError('Out of fuel')
return 'Lesson started'
}
try {
startLesson(0)
} catch (error) {
if (error instanceof NoFuelError) {
console.log('Come back tomorrow, or switch to a premium account')
} else {
throw error
}
}class TextLesson {
constructor(words) {
this.words = words
}
}
class VideoLesson {
constructor(minutes) {
this.minutes = minutes
}
}
function duration(lesson) {
if (lesson instanceof VideoLesson) return lesson.minutes
if (lesson instanceof TextLesson) return Math.ceil(lesson.words / 200)
return 0
}
console.log(duration(new VideoLesson(12)))
console.log(duration(new TextLesson(900)))
console.log(duration({ minutes: 30 }))The plain object { minutes: 30 } has the same field, but it wasn’t created with new VideoLesson(), so instanceof returns false for it.
console.log('text' instanceof String)
console.log(typeof 'text')
console.log([1, 2] instanceof Array)
console.log(Array.isArray([1, 2]))
console.log(null instanceof Object)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- For simple types, use
typeof, and for arrays,Array.isArray(). Saveinstanceoffor classes and errors. - When checking several error classes, start with the most specific one. An instance of
NoFuelErroris also an instance ofError, so the order of the conditions matters. - Instead of a long list of
instanceofconditions, consider a shared method, such asduration(), that each class implements its own way. The code will be shorter and easier to extend.
Related entries
#- classDefines a class: a template for creating objects that share the same fields and methods.
- extendsCreates a derived class that inherits another class’s methods and can extend or override them.
- typeofReturns a string with the name of a value’s type, e.g. "number", "string", or "object".
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- Array.isArray()Checks whether a value is an array.
- ErrorThe built-in error object with a message and a stack trace. The basis for exceptions and custom error classes.
Spotted a mistake or missing an example? Write to us.