🟑 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