Check if Object Instance of Class - Problem

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.

Input & Output

Example 1 — Basic Object Instance
$ Input: obj = {}, classFunction = Object
Output: true
💡 Note: Empty object {} has Object.prototype in its prototype chain, so it's an instance of Object
Example 2 — Null Class Function
$ Input: obj = {}, classFunction = null
Output: false
💡 Note: When classFunction is null, we can't check instanceof, so return false
Example 3 — Number Instance
$ Input: obj = 5, classFunction = Number
Output: true
💡 Note: Number 5 is an instance of the Number constructor function

Constraints

  • No constraints on data types
  • obj or classFunction can be undefined/null
  • Must handle all JavaScript types

Visualization

Tap to expand
Check if Object Instance of Class INPUT obj = { } Empty Object (has prototype chain) classFunction Object Prototype Chain: {} --> Object.prototype --> null (inherits from Object) ALGORITHM STEPS 1 Check Validity Is classFunction callable? 2 Handle Primitives null/undefined return false 3 Use instanceof obj instanceof classFunction 4 Return Result Boolean true or false function checkInstance (obj,cls){ if (cls=== null ) return false return obj instanceof cls } FINAL RESULT true OK Why true? {} is an object Object is a class {} prototype chain includes Object instanceof --> true Output: true Key Insight: The instanceof operator checks if the prototype property of a constructor appears anywhere in the prototype chain of an object. Every plain object {} inherits from Object.prototype, making {} an instance of Object. Handle edge cases: null and undefined cannot use instanceof directly. TutorialsPoint - Check if Object Instance of Class | Built-in instanceof Check
Asked in
Google 35 Facebook 28 Amazon 22
23.4K Views
Medium Frequency
~15 min Avg. Time
856 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