Custom instanceof checks
Quick answer
The right-hand operand of instanceof can provide a Symbol.hasInstance method to define its own membership test.
How it works
candidate instanceof checker first consults checker[Symbol.hasInstance] when available. The returned value is converted to Boolean. The ordinary function implementation typically checks whether its prototype occurs in the left object’s chain (bound functions have special handling). A custom method can accept primitives or ordinary objects independently of prototype ancestry.
const even={ [Symbol.hasInstance](v){return Number.isInteger(v)&&v%2===0;} }; console.log(4 instanceof even,3 instanceof even);Expected output in Node.js:
true falseThe right operand implements its own predicate.
class Box {} const x=Object.create(Box.prototype); console.log(x instanceof Box,Object.hasOwn(x,"constructor"));Expected output in Node.js:
true falsePrototype ancestry can exist without calling the constructor.
Common mistakes
Custom membership is not authentication and may execute code. Do not equate instanceof with checking the actual constructor call history.
Practice
Write a checker for positive integers, then explain why a successful test does not make a number an object.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Custom instanceof checks — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Where is the custom instanceof hook looked up?
What type is the final result of instanceof?
Can ordinary instanceof be true without invoking the constructor?
What is the exact console output in Custom instanceof checks example 1?
const even={ [Symbol.hasInstance](v){return Number.isInteger(v)&&v%2===0;} }; console.log(4 instanceof even,3 instanceof even);What is the exact console output in Custom instanceof checks example 2?
class Box {} const x=Object.create(Box.prototype); console.log(x instanceof Box,Object.hasOwn(x,"constructor"));