MediumObjects📖 Theory Question

How does instanceof work and what are its limitations?

💡

Hint

Walks the prototype chain looking for constructor.prototype — can be fooled

Full Answer

instanceof checks if a constructor's prototype appears anywhere in an object's prototype chain.

class Animal {}
class Dog extends Animal {}

const dog = new Dog();
dog instanceof Dog;    // true — Dog.prototype in chain
dog instanceof Animal; // true — Animal.prototype in chain too
dog instanceof Object; // true — everything inherits from Object

// How it works internally:
// dog.__proto__ === Dog.prototype ✓ → true

// Limitation 1: Can be fooled by setPrototypeOf
const fake = Object.create(Dog.prototype);
fake instanceof Dog; // true — but Dog() was never called!

// Limitation 2: Cross-realm failure
// Arrays from iframes: arr instanceof Array → false!
// Use Array.isArray() — realm-safe

// Limitation 3: Primitives always fail
'hello' instanceof String;     // false (primitive, not object)
new String('hello') instanceof String; // true (wrapped object)

// Better type checking alternatives:
Array.isArray([]);                          // ✅ realm-safe
typeof 'hello';                             // 'string'
Object.prototype.toString.call([]);         // '[object Array]'
💡 instanceof tests the prototype chain, not the constructor. For safe type checks use Array.isArray(), typeof, or Object.prototype.toString.call().

More Objects Questions

EasyHow does prototypal inheritance work in JavaScript?→EasyWhat is the difference between shallow copy and deep copy?→MediumWhat are property descriptors and property flags (writable, enumerable, configurable)?→EasyWhat are getters and setters in JavaScript?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint