Course contentsShow
← JavaScript
Lesson 1014 of 2,72323. SymbolsFree lesson

Symbol.hasInstance for instanceof Behavior

Override how instanceof checks work by implementing Symbol.hasInstance on constructor functions.

Symbol.hasInstance for instanceof Behavior

You'll learn: How to customize what instanceof returns by defining Symbol.hasInstance on a constructor function.

The Default instanceof Check

When you write obj instanceof Constructor, JavaScript normally checks if Constructor.prototype appears anywhere in obj's prototype chain. But what if you want custom logic instead?

Overriding with Symbol.hasInstance

Symbol.hasInstance is a well-known symbol that lets you redefine how instanceof behaves. You define it as a static method on your constructor (or any object used on the right side of instanceof).

How it works:

When JavaScript evaluates obj instanceof MyClass, it actually calls MyClass[Symbol.hasInstance](obj). Whatever that method returns (truthy or falsy) becomes the result.

Example

class SpecialArray {
  static [Symbol.hasInstance](obj) {
    return Array.isArray(obj);
  }
}

const arr = [1, 2, 3];
const notArr = { length: 3 };

console.log(arr instanceof SpecialArray);    // true
console.log(notArr instanceof SpecialArray); // false

Even though arr was never created with new SpecialArray(), our custom check returns true because it's an array.

Why Use It?

This is powerful for:

  • Creating abstract "interface" checks (e.g., "anything array-like")
  • Custom type validation logic
  • Making duck-typing more explicit

Analogy

Think of instanceof as a bouncer at a club. Normally, the bouncer checks IDs by a fixed rule (prototype chain). With Symbol.hasInstance, you become the bouncer and decide who gets in based on any criteria you choose.

Key Takeaway: Symbol.hasInstance lets you override instanceof checks by defining custom logic as a static method on the constructor.