How to check type of an instance in JavaScript?


The instanceof operator determines whether a left-hand side object is created from a specified constructor function in its prototype chain.

object instanceof constructor

  • object = variable name
  • constructor = constructor function name used with the "new" keyword
Example: instanceof
function func1(){  };
function func2(){  };

var f1 = new func1();

f1 instanceof func1; //returns true

f1 instanceof func1; //returns false

f1 instanceof Object; //returns true

Please note that the instanceof operator returns "true" if a variable is initialized with the "new" keyword.

Example: instanceof
var stringObj = new String();
var str = "this is str";

stringObj instanceof String; //returns true
str instanceof String; //returns false

Visit MDN for more information.