JavaScript: “instanceof” Operator

By Xah Lee. Date: . Last updated: .
obj instanceof f
Return true if obj is a child (or child of child …) of f.prototype.
obj must be a Object Type.
f must be a function type.

[see Prototype and Inheritance]

obj instanceof f is basically the same as f.prototype.isPrototypeOf( obj). [see Object.prototype.isPrototypeOf]

// shows how (o instanceof f) is same as ((f.prototype).isPrototypeOf(o))

// define a object with no parent
const root = Object.create(null);

// define a function
function ff() {}

// set the property key prototype
ff.prototype = root;

const obj1 = Object.create(root); // obj1 parent is root
const obj2 = Object.create(obj1); // obj2 parent is obj1
const obj3 = Object.create(obj2); // obj3 parent is obj2

console.log(obj3 instanceof ff); // true

console.log(
  Reflect.apply(Object.prototype.isPrototypeOf, ff.prototype, [obj3])
);
// true

Here's a typical use of instanceof:

// “normal” example of using instanceof

function FF () {
    this.p = 3;
};

const f1 = new FF();

console.log( f1 instanceof FF);              // true
console.log(FF.prototype.isPrototypeOf(f1)); // true

Don't Use “instanceof”

Tip: Avoid using the instanceof operator, because it is not a reliable way to find a object's constructor or type.

(there's no reliable way to find a object's constructor. Objects are often created without constructor, and object's parent can be changed anytime.)

Here's examples where instanceof returns unexpected result.

// example showing “instanceof” isn't really about constructor. It's about prototype chain

// create a constructor function FF
function FF () {return {};}; // returns a object

// create a instance
const f1 = new FF();

console.log( f1 instanceof FF);              // false
console.log(FF.prototype.isPrototypeOf(f1)); // false
// example of “instanceof” with unexpected result

// create a constructor function FF
function FF () {
    this.p = 3;
};

// create a instance
const f1 = new FF();

// change property "prototype"
FF.prototype = [];

console.log( f1 instanceof FF);              // false
console.log(FF.prototype.isPrototypeOf(f1)); // false

If you want to find the subtype of a object, use Object.prototype.toString.call( obj)

[see Determine Type of Object]

If you want to determine if a object is in the prototype chain of another, use isPrototypeOf.

[see Object.prototype.isPrototypeOf]

Don't use property key "constructor".

[see Property Key “constructor”]

JavaScript Constructor/Class

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc