Javascript instanceof operator

Introduction

The typeof operator can determine if a variables a primitive type.

It can determine if a variable is a string, number, Boolean, or undefined.

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

let s = "HTML";
let b = true;/*from   w w  w  . j a v a2  s.c om*/
let i = 22;
let u;
let n = null;
let 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 know is what type of object it is, Javascript provides the instanceof operator.

It is used with the following syntax:

result = variable instanceof constructor 

The instanceof operator returns true if the variable is an instance of the given reference type identified by its prototype chain.

Consider this example:

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

All reference values, by definition, are instances of Object.

So the instanceof operator always returns true when used with a reference value and the Object constructor.

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




PreviousNext

Related