Class Checking in JavaScript with instanceof
The instanceof operator checks whether an object is an instance of a specific class or its parent class.
🔹 Basic instanceof Usage
The syntax is:
Returns true if object is an instance of Class (or a subclass), otherwise false.
✅ Example: Checking an Instance
✔ myDog is an instance of both Dog and Animal due to inheritance.
🔹 Using instanceof with Built-in Classes
✅ Example: Checking Built-in Types
✔ Arrays, Dates, and other objects inherit from Object.
🔹 instanceof with Custom Classes
You can use instanceof to check objects of user-defined classes.
✅ Example: Custom Class Checking
✔ Works the same as built-in classes!
🔹 Overriding instanceof with Symbol.hasInstance
You can customize how instanceof behaves using Symbol.hasInstance.
✅ Example: Custom instanceof Behavior
✔ This makes instanceof return true only for objects with canFly: true.
🔹 instanceof vs. typeof
| Feature | instanceof | typeof |
|---|---|---|
| Works with classes? | ✅ Yes | ❌ No |
| Works with primitives? | ❌ No | ✅ Yes |
| Works with built-in objects? | ✅ Yes | ✅ Yes (but limited) |
✅ Example: typeof vs. instanceof
✔ typeof is for primitives, instanceof is for objects.
🎯 Summary
✔ instanceof checks if an object is an instance of a class or its parents.
✔ Works with custom classes and built-in objects (Array, Date, etc.).
✔ Can be overridden using Symbol.hasInstance.
✔ Use typeof for primitives (string, number, etc.).
🚀 Need help with instanceof? Let me know! 😊

