#2618
Medium JavaScript Check if object instance of class
29.1% acceptance
Mar 2, 2026
293
111
Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.
There are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined.
Solution
TypeScript
Time O(n)
Space O(1)
function checkIfInstanceOf(obj: any, classFunction: any): boolean {
if (
obj === null ||
obj === undefined ||
classFunction === null ||
classFunction === undefined
) {
return false;
}
let proto = Object.getPrototypeOf(Object(obj));
while (proto !== null) {
if (proto === classFunction.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
/**
* checkIfInstanceOf(new Date(), Date); // true
*/