Check if Object Instance of Class - Problem

Write a function that determines if a given value is an instance of a given class or its superclass. This problem tests your understanding of JavaScript's prototype chain and inheritance model.

For this problem, an object is considered an instance of a class if:

  • The object has access to that class's methods through the prototype chain
  • The class appears anywhere in the object's prototype hierarchy

Important: Your function must handle any data types - including undefined, null, primitives, objects, functions, or classes. This makes the problem more challenging than simply using the built-in instanceof operator.

Goal: Return true if the value is an instance of the class, false otherwise.

Input & Output

example_1.js โ€” Basic Class Inheritance
$ Input: checkIfInstanceOf(new Date(), Date)
โ€บ Output: true
๐Ÿ’ก Note: A Date instance is indeed an instance of the Date class, so we return true
example_2.js โ€” Null/Undefined Cases
$ Input: checkIfInstanceOf(null, Array)
โ€บ Output: false
๐Ÿ’ก Note: Null values are not instances of any class, so we return false
example_3.js โ€” Custom Class Inheritance
$ Input: class Animal {} class Dog extends Animal {} checkIfInstanceOf(new Dog(), Animal)
โ€บ Output: true
๐Ÿ’ก Note: A Dog instance inherits from Animal through the prototype chain, so it's considered an instance of Animal

Constraints

  • The function must handle null and undefined values
  • The class parameter can be any type, not just functions
  • Must work with built-in classes like Date, Array, Object
  • Must work with custom classes and inheritance chains
  • No use of built-in instanceof operator allowed

Visualization

Tap to expand
myObject{name: 'test'}Child.prototypeconstructor: ChildParent.prototypeconstructor: ParentObject.prototypetoString, valueOfnullJavaScript Prototype Chain Traversal1234Algorithm: Start at object โ†’ Get prototype โ†’ Compare with target โ†’ Continue up chain โ†’ Return true if foundTime: O(d) where d is prototype chain depth | Space: O(1) constant space
Understanding the Visualization
1
Validate Inputs
Check if object exists and class is a valid function
2
Get Starting Point
Obtain the object's immediate prototype using Object.getPrototypeOf()
3
Walk the Chain
Follow prototype links upward, comparing each level with target
4
Match or End
Return true if match found, false if we reach null
Key Takeaway
๐ŸŽฏ Key Insight: JavaScript's prototype chain creates a natural hierarchy that we can traverse upward to check inheritance relationships without using the instanceof operator.
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
23.8K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen