Skip to content

JavaScript instanceof operator | Check type of object

  • by

The JavaScript instanceof operator is used to check the type of an object at the run time. The return value is a boolean value. The instanceof operator tests the presence of constructor.prototype in object‘s prototype chain.

var myVar = objectName instanceof objectType

One thing worth mentioning is instanceof evaluates to true if the object inherits from the class’s prototype:

var p = new Person("Jon");
p instanceof Person

That is p instanceof Person is true since p inherits from Person.prototype.

JavaScript instanceof operator

A simple example code checks the current object and returns true if the object is of the specified object type.

<!DOCTYPE html>
<html>
<body>

  <script>

   var color1 = new String("green");
   console.log(color1 instanceof String); 

   var color2 = "coral"; 
   console.log(color2 instanceof String); 

 </script>

</body>
</html> 

Output:

JavaScript instanceof operator

The Instanceof operator also takes inheritance into account. It returns true if the object inherits from the classes’ prototype.

Example code returns true if obj belongs to the Class or a class inheriting from it.

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car);
// true

console.log(auto instanceof Object);
// true

Another example

class Person {
  constructor(name) {
    this.name = name;
  }
}

class Student extends Person {
  constructor(name, grade) {
    super(name);
    this.grade = grade;
  }
}

const john = new Person('John');
const jane = new Student('Jane', 10);

console.log(john instanceof Person);   // true
console.log(john instanceof Student);  // false

console.log(jane instanceof Person);   // true
console.log(jane instanceof Student);  // true

In the example above, we have two classes, Person and Student, where Student is a subclass of Person. By using the instanceof operator, we can determine whether an object is an instance of a particular class or its subclass.

Comment if you have any doubts or suggestions on this JS Operator example.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading