Sub topic 11
Customizing instanceof with Symbol.hasInstance
This chapter assumes you know ES6 classes and static methods, and how prototype chains work. It also assumes you have read the earlier chapter on well-known symbols. You will see how instanceof actually decides its answer, how Symbol.hasInstance replaces that decision, and the traps that make this hook easy to misuse.
How instanceof Decides by Default
When you write value instanceof C, most developers picture a prototype-chain walk. The engine checks whether C.prototype appears anywhere in the chain of value. That walk is only the fallback. The specification first asks the right-hand side a question: do you have a Symbol.hasInstance method?
The full algorithm for value instanceof target is:
- If
targetis not an object, throw aTypeError. - Look up
target[Symbol.hasInstance]. The lookup follows the prototype chain oftargetitself. - If that method exists, call it with
thisset totargetandvalueas the argument. Convert the result to a boolean and return it. - If no method exists and
targetis not callable, throw aTypeError. - Otherwise, run the ordinary prototype-chain walk.
There is a detail that explains a lot of the behavior below. Every function already has a Symbol.hasInstance method, inherited from Function.prototype. That inherited method is what runs the prototype-chain walk. So for ordinary classes, step 3 always fires and simply calls the default.
console.log(typeof Function.prototype[Symbol.hasInstance]); // "function"
class Point {}
const p = new Point();
console.log(p instanceof Point); // true
console.log(Function.prototype[Symbol.hasInstance].call(Point, p)); // trueOverriding the Check with a Static Method
To change what instanceof means for a class, define a static method under Symbol.hasInstance. It is static because instanceof looks up the hook on the constructor, not on instances.
class Even {
static [Symbol.hasInstance](value) {
return Number.isInteger(value) && value % 2 === 0;
}
}
console.log(2 instanceof Even); // true
console.log(3 instanceof Even); // false
console.log(new Even() instanceof Even); // falseThe last line looks odd. An object built by new Even() is not "an instance of Even" anymore, because the hook replaced the prototype check completely. Nothing about the default survives unless you call it yourself.
The example also shows that the left side can be a primitive. The default check returns false for every primitive, since primitives have no prototype chain of their own. A custom hook gets the raw primitive and can say anything about it.
The Return Value Is Coerced
The engine converts whatever your hook returns with the same truthiness rules as if. Returning 'no' produces true, and returning 0 or undefined produces false. Return a real boolean so readers don't have to work this out.
class Sloppy {
static [Symbol.hasInstance]() {
return 'no';
}
}
console.log(null instanceof Sloppy); // true, because 'no' is truthyGotcha: You Cannot Assign the Hook to a Function
The inherited Function.prototype[Symbol.hasInstance] property is non-writable and non-configurable. When an inherited property is non-writable, plain assignment cannot create an own property that shadows it. In sloppy mode the assignment fails silently. In strict mode, which includes every ES module and class body, it throws.
'use strict';
function Legacy() {}
try {
Legacy[Symbol.hasInstance] = () => true;
} catch (e) {
console.log(e instanceof TypeError); // true
}
Object.defineProperty(Legacy, Symbol.hasInstance, {
value: () => true
});
console.log({} instanceof Legacy); // trueThe static syntax in a class works because class definitions create properties with define semantics rather than assignment. For constructor functions written the old way, use Object.defineProperty.
Gotcha: Subclasses Inherit the Hook
Static methods are inherited through the constructor's own prototype chain: Object.getPrototypeOf(Child) === Parent. So a subclass picks up the parent's hook, often by surprise.
class Even {
static [Symbol.hasInstance](value) {
return Number.isInteger(value) && value % 2 === 0;
}
}
class TaggedEven extends Even {}
console.log(4 instanceof TaggedEven); // true (inherited hook)
console.log(new TaggedEven() instanceof TaggedEven); // falseIf the custom rule should apply only to the base class, check this, which is the right-hand side of the instanceof. Fall back to the default for everything else.
class Even {
static [Symbol.hasInstance](value) {
if (this !== Even) {
return Function.prototype[Symbol.hasInstance].call(this, value);
}
return Number.isInteger(value) && value % 2 === 0;
}
}
class TaggedEven extends Even {}
console.log(4 instanceof Even); // true
console.log(4 instanceof TaggedEven); // false
console.log(new TaggedEven() instanceof TaggedEven); // trueCalling Function.prototype[Symbol.hasInstance].call(this, value) is the standard way to get the original behavior back inside an override.
The Right-Hand Side Does Not Have to Be a Class
Step 4 of the algorithm only demands a callable target when there is no hook. A plain object with a Symbol.hasInstance method is a valid right-hand side. You can use this to write readable duck-typing checks:
const Iterable = {
[Symbol.hasInstance](value) {
return value != null && typeof value[Symbol.iterator] === 'function';
}
};
console.log([1, 2] instanceof Iterable); // true
console.log(new Map() instanceof Iterable); // true
console.log('abc' instanceof Iterable); // true (strings are iterable)
console.log(42 instanceof Iterable); // false
console.log({} instanceof Iterable); // falseWithout the hook, [] instanceof {} throws TypeError: Right-hand side of 'instanceof' is not callable. With the hook, the object works as a type predicate.
A Stronger Brand Check with Private Fields
The default check is easy to fool. Object.create(C.prototype) produces an object that passes instanceof C without the constructor ever running. Object.setPrototypeOf can also make a real instance fail the check. A hook can use a private-field in check (ES2022), which tests whether the constructor actually ran on the object:
class Token {
#brand = true;
static [Symbol.hasInstance](value) {
return typeof value === 'object' && value !== null && #brand in value;
}
}
const real = new Token();
const fake = Object.create(Token.prototype);
console.log(real instanceof Token); // true
console.log(fake instanceof Token); // false (the default would say true)
Object.setPrototypeOf(real, null);
console.log(real instanceof Token); // true (the default would say false)The typeof guard matters: #brand in value throws a TypeError when value is a primitive.
What the Hook Does Not Change
Symbol.hasInstance affects the instanceof operator and nothing else. Other code paths that reason about prototypes ignore it.
| Mechanism | Uses Symbol.hasInstance? |
|---|---|
| `value instanceof C` | Yes |
| `C.prototype.isPrototypeOf(value)` | No, always walks the prototype chain |
| `Object.getPrototypeOf(value) === C.prototype` | No |
| `Array.isArray(value)` | No, checks an internal marker |
| TypeScript narrowing after `instanceof` | Narrows to `C` anyway, which can be wrong at runtime |
That last row deserves attention. TypeScript assumes x instanceof Even means x has type Even. With the hook above, x is really a number. The type checker is now confidently wrong, so a custom hook in a typed codebase usually needs a matching type predicate function.
Cross-Realm Values
Each realm (an iframe, a Node vm context, a worker) has its own copy of the built-in constructors. An array from an iframe fails instanceof Array in the parent page, because its prototype is the iframe's Array.prototype. A custom hook can fix this for your own types by checking structure or a registered symbol from Symbol.for, which is shared across realms, instead of prototype identity:
const BRAND = Symbol.for('my-lib.Money');
class Money {
constructor(cents) {
this.cents = cents;
this[BRAND] = true;
}
static [Symbol.hasInstance](value) {
return value != null && value[BRAND] === true;
}
}
console.log(new Money(500) instanceof Money); // true
console.log({ [Symbol.for('my-lib.Money')]: true } instanceof Money); // trueThe second line shows the trade-off. Any code can forge the brand, because registered symbols are public by design. Cross-realm recognition and forgery resistance pull in opposite directions. Private fields resist forgery but only work within one realm. Registered symbols work across realms but anyone can fake them.
Decision Criteria
Overriding instanceof changes what a familiar operator means. Readers who see x instanceof Foo will assume a prototype check unless they go looking. Use the hook when:
- You publish a type whose identity must survive realms or duplicated package copies (two versions of a library in
node_modules), and you accept that a symbol brand can be forged. - You want a brand check that
Object.createcannot fool, and the class should own that rule. - You are building a small predicate object such as
Iterableand theinstanceofsyntax actually reads better than a function call.
Prefer a plain function such as isMoney(value) or a static Money.isMoney(value) when the check is mainly validation logic. Functions are explicit, type checkers understand them as predicates, and they cannot be inherited by surprise. Engines also optimize the default instanceof path heavily. A custom hook adds a function call to every check, which only matters in very hot code.
Exercise
Given class Base { static [Symbol.hasInstance](v) { return typeof v === 'string'; } } and class Child extends Base {}, what do 'hi' instanceof Child and new Child() instanceof Child print, and why?
Show answer
'hi' instanceof Child is true and new Child() instanceof Child is false. Child inherits the static hook from Base through its constructor prototype chain, so instanceof Child runs the string test, and an object is not a string. To restore the normal check for subclasses, compare this to Base inside the hook and call Function.prototype[Symbol.hasInstance].call(this, v) when they differ.
Exercise
A teammate writes function User() {} followed by User[Symbol.hasInstance] = v => v && typeof v.id === 'number'; in a sloppy-mode script. ({ id: 1 }) instanceof User returns false. Explain the cause and give a fix.
Show answer
Function.prototype[Symbol.hasInstance] is non-writable, so plain assignment cannot create an own property that shadows it. In sloppy mode the assignment silently does nothing, and the default prototype check still runs. Fix it with Object.defineProperty(User, Symbol.hasInstance, { value: v => v != null && typeof v.id === 'number' }), or convert User to a class with a static [Symbol.hasInstance] method.
Exercise
Write a plain object PositiveNumber so that 5 instanceof PositiveNumber is true, while -1 instanceof PositiveNumber and '5' instanceof PositiveNumber are false. Why does this not throw even though PositiveNumber is not a function?
Show answer
const PositiveNumber = { [Symbol.hasInstance](v) { return typeof v === 'number' && v > 0; } }; It does not throw because instanceof only requires a callable right-hand side when no Symbol.hasInstance method is found. Here the hook exists, so the engine calls it and never reaches the callability check.