Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 6

Symbol.hasInstance for Custom instanceof Behavior

This lesson is built with resources from youtube.com, developer.mozilla.org and 1 more site.

Hello! In our last lesson, we explored Symbol.species and saw how it gives us control over what kind of object is created by methods like .slice() on a subclass. We're continuing our journey through JavaScript's well-known symbols, which act as hooks into the language's internal algorithms.

Today, we'll focus on one of the most fundamental operators in object-oriented JavaScript: instanceof. You've likely used it countless times to check if an object was created from a specific class. But what if you could redefine what "instance of" means for your own classes?

That's precisely our goal for this lesson. Your learning outcome is to: Customize the behavior of the 'instanceof' operator for a class using Symbol.hasInstance.

We will cover:

  • How the instanceof operator really works behind the scenes.
  • How to implement a custom static [Symbol.hasInstance] method to define your own type-checking logic.
  • A deeper look into why certain methods of defining this property work while others fail, touching on property descriptors and the prototype chain.

1. Demystifying the instanceof Operator

Traditionally, we think of object instanceof Constructor as a check that walks up object's prototype chain to see if Constructor.prototype exists there. While this is the default behavior, it's not the whole story.

Since ES2015, the instanceof operator's logic is actually delegated to a method on the constructor (the right-hand operand). This method is identified by the well-known symbol Symbol.hasInstance.

The expression obj instanceof Ctor is, under the hood, roughly equivalent to Ctor[Symbol.hasInstance](obj). The JavaScript engine first looks for a [Symbol.hasInstance] method on the constructor. If found, it calls it with the object as an argument and returns the result. If not found, it falls back to the default prototype chain check.

The following video clip provides a concise demonstration of this internal mechanism.

JavaScript Symbols MasterClass // The Missing Guide

The video 'JavaScript Symbols MasterClass' from the channel basarat provides a great visual for how instanceof relates to Symbol.hasInstance.

Please watch from 04:37 to 05:08. This segment shows the standard instanceof check and then demonstrates that calling ClassName[Symbol.hasInstance](instance) yields the exact same result, revealing the underlying operation.

This hook is what gives us the power to create our own definition of "instance."


2. Implementing Custom instanceof Logic

To customize the instanceof check, you define a static method on your class using the computed property name [Symbol.hasInstance]. This method will receive one argument—the object being tested—and your code should return true or false.

This allows you to perform checks that go beyond the prototype chain. For example, you can check for the presence of specific properties or values, a pattern sometimes known as "duck typing."

Let's look at a very clear example. What if we wanted to check if a number is an instance of a conceptual class Even? A number can't have Even in its prototype chain, but with Symbol.hasInstance, we can make it work.

Customizing `instanceof` with `Symbol.hasInstance`
This image shows two ways to define custom `instanceof` logic for an 'Even' concept. The left uses a class with a static `[Symbol.hasInstance]` method, and the right uses a plain object. Both check if a value is a number and if it's divisible by 2. This allows `2 instanceof Even` to correctly return `true`.

This technique is powerful for creating flexible APIs or for working with objects that may not share a common class inheritance structure but do share a common interface or characteristics.

The next video clip walks through a practical implementation for an ArrayLike class, which identifies any object as an "instance" if it is an array or has a numeric length property.

JavaScript Symbols MasterClass // The Missing Guide

Let's watch a practical coding example from the same 'JavaScript Symbols MasterClass' video.

Watch from 05:08 to 05:55. The presenter builds a class called ArrayLike and implements a [Symbol.hasInstance] method to define what qualifies as an 'array-like' object for the instanceof operator.


3. A Deeper Dive: Property Descriptors and Function.prototype

Given your background in computer science, you might be wondering about the mechanics here. Why do we need the static keyword or, in older-style code, Object.defineProperty? Why can't we just assign the method directly to a constructor function like this?

function MyClass() {}

// This will NOT work as expected!
MyClass[Symbol.hasInstance] = function(instance) {
  // custom logic
  return instance.hasOwnProperty('mySpecialProperty');
};

const obj = { mySpecialProperty: true };
console.log(obj instanceof MyClass); // false

The code above fails. The instanceof check will still use the default prototype-based logic. The reason for this is a classic JavaScript subtlety involving the prototype chain and property descriptors.

Every function in JavaScript inherits from Function.prototype. It turns out that Function.prototype has its own Symbol.hasInstance property, and crucially, its writable attribute is set to false.

// You can inspect this yourself in a browser console
Object.getOwnPropertyDescriptor(Function.prototype, Symbol.hasInstance);

/*
{
  value: Æ’ [Symbol.hasInstance](),
  writable: false, // <-- This is the key
  enumerable: false,
  configurable: false
}
*/

When you use an assignment (=), the engine first checks the prototype chain for a property with the same name. It finds the non-writable Symbol.hasInstance on Function.prototype. Because it's non-writable, the assignment to the MyClass object silently fails in non-strict mode (and throws a TypeError in strict mode). Your new function is never assigned.

The following Stack Overflow answer explains this behavior perfectly.

Definition of custom `@@hasInstance` method in Javascript

This Stack Overflow Q&A, 'Definition of custom @@hasInstance method in Javascript', provides an excellent, in-depth explanation for why direct assignment fails.

Read the accepted answer by Nick Parsons. It clearly shows the property descriptor for Function.prototype[Symbol.hasInstance], uses a simple analogy with a non-writable property to explain the behavior, and clarifies why Object.defineProperty (which is used by the static class syntax) works where assignment fails. Focus on understanding the role of the writable: false attribute.

In summary:

  • Assignment (=) checks the prototype chain. If an inherited property is non-writable, the assignment to create a new "shadowing" property on the object fails.
  • Object.defineProperty() (and by extension, static class syntax) operates directly on the target object. It doesn't consult the prototype chain in the same way, so it can successfully define a new own-property, even if an inherited property with the same name is non-writable.
Test your understanding!

Drawing from your interest in anime and manga, let's create a utility object called IsekaiProtagonist. An object should be considered an "instance" of IsekaiProtagonist if it meets the following "isekai" criteria:

  1. It has a property transportedFrom which is equal to the string 'Earth'.
  2. It has a property hasSpecialPower which is true.

Your task is to implement the IsekaiProtagonist object below so that the instanceof checks work as described.

const IsekaiProtagonist = {
  // YOUR IMPLEMENTATION HERE
};

const kirito = {
  name: 'Kirito',
  transportedFrom: 'Earth',
  hasSpecialPower: true
};

const naruto = {
  name: 'Naruto',
  transportedFrom: 'Konoha', // Not from Earth
  hasSpecialPower: true
};

const someGuy = {
  name: 'Bob',
  transportedFrom: 'Earth',
  hasSpecialPower: false // No special power
};

// This should be TRUE
console.log('Is Kirito an Isekai Protagonist?', kirito instanceof IsekaiProtagonist);

// This should be FALSE
console.log('Is Naruto an Isekai Protagonist?', naruto instanceof IsekaiProtagonist);

// This should be FALSE
console.log('Is Bob an Isekai Protagonist?', someGuy instanceof IsekaiProtagonist);
Show answer

You need to add a [Symbol.hasInstance] method to the IsekaiProtagonist object that checks for the required properties.

const IsekaiProtagonist = {
  [Symbol.hasInstance](instance) {
    return instance.transportedFrom === 'Earth' && instance.hasSpecialPower === true;
  }
};

const kirito = {
  name: 'Kirito',
  transportedFrom: 'Earth',
  hasSpecialPower: true
};

const naruto = {
  name: 'Naruto',
  transportedFrom: 'Konoha',
  hasSpecialPower: true
};

const someGuy = {
  name: 'Bob',
  transportedFrom: 'Earth',
  hasSpecialPower: false
};

console.log('Is Kirito an Isekai Protagonist?', kirito instanceof IsekaiProtagonist); // true

console.log('Is Naruto an Isekai Protagonist?', naruto instanceof IsekaiProtagonist); // false

console.log('Is Bob an Isekai Protagonist?', someGuy instanceof IsekaiProtagonist); // false

Conclusion

In this lesson, we peeled back the curtain on the instanceof operator and took control of its behavior. This is a powerful metaprogramming technique that lets you define type relationships based on an object's structure or content (duck typing) rather than being strictly limited to its inheritance lineage.

Key Takeaways:

  • The instanceof operator's behavior is determined by the [Symbol.hasInstance] static method on the right-hand operand (the constructor).
  • By implementing this method on your class or object, you can define custom logic that determines if another object should be considered its "instance."
  • You must use static syntax in a class or Object.defineProperty because Function.prototype has a non-writable [Symbol.hasInstance] property that prevents simple assignment from working on constructor functions.

Next Up

We've now seen several well-known symbols that are attached to objects and classes to modify behavior. But how do you discover which symbols an object is using? Regular methods like Object.keys() or a for...in loop won't reveal symbol properties. In our next lesson, we will learn how to retrieve all property symbols from an object using Object.getOwnPropertySymbols(), giving us a complete picture of an object's properties.