Javascript - Object instanceof operator


The typeof operator is the best way to determine if a variable is a primitive type: a string, number, Boolean, or undefined.

If the value is an object or null, then typeof returns "object":

var s = "First";
var b = true;
var i = 22;
var u;
var n = null;
var o = new Object();

console.log(typeof s);   //string
console.log(typeof i);   //number
console.log(typeof b);   //boolean
console.log(typeof u);   //undefined
console.log(typeof n);   //object
console.log(typeof o);   //object

To get the type of object, use instanceof operator:

result = variable instanceof constructor

The instanceof operator returns true if the variable is an instance of the given reference type.

Consider this example:

console.log(person instanceof Object);   //is the variable person an Object?
console.log(myValues instanceof Array);  //is the variable myValues an Array?
console.log(pattern instanceof RegExp);  //is the variable pattern a RegExp?

All reference values are instances of Object, so the instanceof operator always returns true when used with a reference value and the Object constructor.

If instanceof is used with a primitive value, it will always return false, because primitives aren't objects.

The typeof operator also returns "function" when used on a function.