JavaScript instanceof operator

In this article, we shall look at the instanceof operator and understand what it actually does with examples.

Table of Contents


What is Instanceof?

The JavaScript instanceof operator is used to check the type of an object at the run time. It returns a boolean value(true or false). If the returned value is true, then it indicates that the object is an instance of a particular class and if the returned value is false then it is not.

Syntax and explanation

Syntax:
var myVar = objectName instanceof objectType


Parameters:
objectName: Signifies the name of the object.

Example:
var  = ["Apple", "Mango", "Banana"];

console.log(fruits instanceof Array);
console.log(fruits instanceof Object);
console.log(fruits instanceof Number);
console.log(fruits instanceof String);

//Output
true
true
false
false


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

obj instanceof Class
It returns true if obj belongs to the Class or a class inheriting from it.

class Flexiple {}
let flexiple = new Flexiplet();

// is it an object of Flexiple class?
alert( flexiple instanceof Flexiple ); // true

Similarly, it also works with constructor functions.


Why do we need instanceof in JavaScript?

In JavaScript when we declare a variable, we don't explicitly define a type. i.e. we just use var xyz; which could be a string, number, array, or a user-defined datatype as opposed to other languages, for example, in C or C+ we specify the datatype while declaring a variable i.e. int i; float f, etc. Hence, having instanceof operator to check if an object belongs to a certain specified type would be useful in JavaScript.