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
nullandundefinedvalues - 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
instanceofoperator allowed
Visualization
Tap to expand
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code