JavaScript “instanceof” Operator

By Xah Lee. Date: . Last updated: .

JavaScript has a instanceof operator. The syntax is obj instanceof f.

obj instanceof f returns true if obj is a child (or child of child …) of the value of f.prototype . 〔►see JavaScript: Prototype and Inheritance

obj instanceof f is the same as f.prototype.isPrototypeOf(obj).

〔►see JavaScript: Find Object's Prototype

ECMAScript 2015 §ECMAScript Language: Expressions#sec-instanceofoperator

// “normal” example of using instanceof

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

var f1 = new FF();

console.log( f1 instanceof FF);              // true
console.log(FF.prototype.isPrototypeOf(f1)); // true
// artificial example of using instanceof to return true

function ff () {};
var x = {};

ff.prototype = Object.prototype;

console.log( x instanceof ff);              // true
console.log(ff.prototype.isPrototypeOf(x)); // true

Warning: instanceof is not reliable for checking if a function is a object's constructor. (there's no way to do that reliably) 〔►see JavaScript: What's Constructor?

// 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
var 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
var f1 = new FF();

// change this value
FF.prototype = [];

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

Avoid Using the 「instanceof」 Operator

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, because JavaScript does not have the concept of “class” as in {Java, Python, Ruby}. Objects are often created without constructor, and object's parent can be changed anytime.)

If you want to find the subtype of a object, use Object.prototype.toString(). See: JavaScript: Determine Type of Object.

If you want to determine if a object is in the prototype chain of another, use isPrototypeOf. See: JavaScript: Find Object's Prototype.

Avoid using constructor property too. See: JavaScript: Property Key "constructor".

JS Constructor Topic

  1. JavaScript: Keyword “this”
  2. JavaScript: What's Constructor?
  3. JavaScript: Property Key "prototype"
  4. JavaScript: Operator “new”
  5. JavaScript “instanceof” Operator
  6. JavaScript: How to Use Object.create() to Emulate Constructor?
  7. JavaScript: Property Key "constructor"
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.