JavaScript instanceof Example

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
The JavaScript instanceof operator returns true if the first operand is an instance of the object passed on the right or one of its ancestors in its prototype chain.

Example 1 - Simple instanceof Operator Example

class Person{
    firstName;
    lastName;
}

class Employee extends Person{

}

class Manager extends Person{

}

function testInstanceOfOperator(){
    const employee = new Employee();
    const manager = new Manager();

    // should print true
    console.log(employee instanceof Employee);
    console.log(employee instanceof Person);

    console.log(manager instanceof Manager);
    console.log(manager instanceof Person);

    // should print false
    console.log(manager instanceof Employee);
    console.log(employee instanceof Manager);
}

testInstanceOfOperator();
Output:
true
true
true
true
false
false
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
You can refer below screenshot for your testing:

Example - Demonstrating that String and Date are of type Object and exceptional cases

The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object).
var simpleStr = 'This is a simple string'; 
var myString  = new String();
var newStr    = new String('String created with constructor');
var myDate    = new Date();
var myObj     = {};
var myNonObj  = Object.create(null);

simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
myString  instanceof String; // returns true
newStr    instanceof String; // returns true
myString  instanceof Object; // returns true

myObj    instanceof Object;    // returns true, despite an undefined prototype
({})     instanceof Object;    // returns true, same case as above
myNonObj instanceof Object;    // returns false, a way to create an object that is not an instance of Object

myString instanceof Date;   // returns false

myDate instanceof Date;     // returns true
myDate instanceof Object;   // returns true
myDate instanceof String;   // returns false

Example 3 - Demonstrating that mycar is of type Car and type Object

The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
var mycar = new Car('Honda', 'Accord', 1998);
var a = mycar instanceof Car;    // returns true
var b = mycar instanceof Object; // returns true

Comments