Glossary / instanceof

instanceof

instanceof normally checks whether a constructor’s prototype object occurs anywhere in the tested object’s prototype chain. It answers a prototype-relationship question, not “does this data have the right shape?” The operator can also be customized by a constructor’s Symbol.hasInstance method, so custom behavior is possible.

Prototype-chain behavior

class Animal {}
class Cat extends Animal {}
const cat = new Cat();

cat instanceof Cat;    // true
cat instanceof Animal; // true

The operator is realm-sensitive. An array created in another iframe has a different realm’s Array.prototype, so it may fail value instanceof Array; Array.isArray(value) is the robust array check. Changing Constructor.prototype after instances exist can also change subsequent results. Primitive values are not instances of their wrapper constructors in the way some languages might suggest ("x" instanceof String is false).

Do not use instanceof to validate JSON or untrusted input: parsed JSON objects usually have ordinary prototypes, and attackers can control fields. Validate required properties, types, ranges, and discriminants. For application classes, instanceof can be reasonable inside one controlled realm when the class identity itself is meaningful.

Interview questions

  1. What does instanceof check? The constructor’s prototype relationship in the object’s prototype chain, unless customized by Symbol.hasInstance.
  2. Why can an iframe array fail instanceof Array? It uses a different realm and a different Array prototype object.
  3. What is the cross-realm array check? Array.isArray.
  4. Does instanceof validate object fields? No; it tests prototype relationship, not schema validity.

References