Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

What is instanceof in Javascript

In this chapter, you will learn about what is instanceof in Javascript. In simple words,

The instanceof operator helps to check whether the LHS object name is belongs to the specific data type or class.

Technically, the instanceof operator checks whether the prototype of a constructor appears in the prototype chain of an object.

The instanceof operator returns the boolean value, either true or false.

Lets see the syntax:
objectName instanceof constructor/class/function

function Employee(name, email, address) {
  this.name = name;
  this.email = email;
  this.address = address;
}

const john = new Employee('John', 'John@john.com', 'Street 3');

console.log(john instanceof Employee);
console.log(john instanceof Object);

// Output
// true
// true

Now we will check for different data types,

function Employee(name, email, address) {
  this.name = name;
  this.email = email;
  this.address = address;
}

const john = new Employee('John', 'John@john.com', 'Street 3');

console.log(john instanceof Employee);
console.log(john instanceof String);

// Output
// true
// false