Magicsheet logo

Check if Object Instance of Class

Medium
12.5%
Updated 8/1/2025

Asked by 2 Companies

Topics

Check if Object Instance of Class

What is this problem about?

This problem is common in JavaScript and TypeScript environments. It asks you to implement a function that checks if a given object is an instance of a specific class or constructor function. The check should account for the entire prototype chain, meaning if the object belongs to a subclass of the target class, it should still return true.

Why is this asked in interviews?

Interviews at Microsoft and Google often include this to test a developer's deep understanding of the language's object-oriented principles. In JavaScript, inheritance is handled via prototypes, not traditional classes. Knowing how to traverse the __proto__ chain or use instanceof correctly is crucial for building robust libraries and debugging complex object hierarchies.

Algorithmic pattern used

The pattern used here is Prototype Chain Traversal. You start with the object's prototype and move up the chain one level at a time. At each step, you compare the current prototype with the prototype property of the target class. If they match, you've found an instance. If you reach null, you've reached the end of the chain without finding a match.

Example explanation

Let's say we have a class Animal and a subclass Dog.

  • let myDog = new Dog();
  • Is myDog an instance of Animal?
  1. The engine looks at myDog.__proto__ (which is Dog.prototype).
  2. It doesn't match Animal.prototype.
  3. It moves up to myDog.__proto__.__proto__ (which is Animal.prototype).
  4. Now it matches! The function returns true.

Common mistakes candidates make

One major pitfall is not handling edge cases like null or undefined inputs. Another is failing to realize that the prototype of a primitive (like a string) can still be compared to the global String class if handled correctly. Some candidates also forget that the prototype chain is not an array, but a series of linked references.

Interview preparation tip

Spend some time learning the difference between Object.getPrototypeOf(obj) and the .prototype property of a constructor. Understanding how JavaScript links objects under the hood is a "high-signal" skill that distinguishes senior engineers from juniors.

Similar Questions