Introduction
In javascript, though it seems like typeof and instanceof are similar, they are different operators, and they have different use-cases. Typeof operator checks the primitive type of a value, whereas instanceof checks if the value is an instance of a class or class function. Here we will look into how instanceof works and its differences with typeof operator.
instanceof
instanceof operator checks if the constructor’s prototype appears anywhere in the object’s prototype chain. It returns a boolean value, true or false.
In simple words, it can be said that if a value is an instance of a class or class function, it returns true otherwise false.
Syntax
object instanceof class
Here, the object is the value that needs to be checked, and the class is the class or function to check against.
Example
class Student
{
constructor(name, enr_no)
{
this.name=name;
this.enr_no=enr_no;
}
};
var student1 = new Student("Ninja",510519);
console.log(student1 instanceof Student);
Output
true
Use cases
instanceof for prototype checking
instanceof operator checks the presence of constructor.prototype in object’s prototype chain.
class Student
{
constructor(name, enr_no)
{
this.name=name;
this.enr_no=enr_no;
}
};
function Scholar() {}
Scholar.prototype = new Student();
let obj= new Scholar();
console.log(obj instanceof Student);
// Student.prototype is now in obj's prototype chain
Output
true
Using with strings
String literals are not instance of a String class but a string created with a string constructor is an instance of a string class.
var str1 = 'Coding Ninjas';
//string literal not instance of String class
console.log(str1 instanceof String);
var str2 =new String('Coding Ninjas Studio');
console.log(str2 instanceof String);
Output
false
true
Object created using Object.create() function
instanceof operator also works for object created using Object.create( ) function.
Let’s visualize this through examples
class Student
{
constructor(name, enr_no)
{
this.name=name;
this.enr_no=enr_no;
}
};
function Scholar() {}
Scholar.prototype = Object.create(Student.prototype);
let obj= new Scholar();
console.log(obj instanceof Student);
// Student.prototype is now in obj's prototype chain
Output
true