JavaScript Tutorial JavaScript References

JavaScript - instanceof Operator



The JavaScript instanceof operator checks if an object is an instance of a specific class. It returns true if the object is an instance of a specific class, false otherwise.

Syntax

objectName instanceof objectType

Return Value

Returns true if the object is an instance of a specific class, false otherwise.

Example:

The example below shows the usage of instanceof operator.

var Num = [10, 20, 30];
var txt;

//using instanceof operator
txt = "Num instanceof Array : " + 
      (Num instanceof Array) + "<br>";
txt = txt + "Num instanceof Object : " + 
      (Num instanceof Object) + "<br>";
txt = txt + "Num instanceof Number : " + 
      (Num instanceof Number) + "<br>";
txt = txt + "Num instanceof String : " + 
      (Num instanceof String) + "<br>";

The output (value of txt) after running above script will be:

Num instanceof Array : true
Num instanceof Object : true
Num instanceof Number : false
Num instanceof String : false

Example:

Lets consider one more example, where string and dates objects are used with instanceof operator.

var Str = new String();
var Dt = new Date();
var txt;

//using instanceof operator
txt = "Str instanceof Object : " + 
      (Str instanceof Object) + "<br>";
txt = txt + "Str instanceof Number : " + 
      (Str instanceof Number) + "<br>";
txt = txt + "Str instanceof String : " + 
      (Str instanceof String) + "<br>";
txt = txt + "Dt instanceof Object : " + 
      (Dt instanceof Object) + "<br>";
txt = txt + "Dt instanceof Date : " + 
      (Dt instanceof Date) + "<br>";
txt = txt + "Dt instanceof String : " + 
      (Dt instanceof String) + "<br>";

The output (value of txt) after running above script will be:

Str instanceof Object : true
Str instanceof Number : false
Str instanceof String : true
Dt instanceof Object : true
Dt instanceof Date : true
Dt instanceof String : false

❮ JavaScript - Operators