Use instanceof operator to determine type for reference type variable

Description

To identify what type of object it is, Javascript provides the instanceof operator, which is used with the following syntax:

var booleanResult = variable instanceof constructor

Example

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


//(person instanceof Object);   //is the variable person an Object?
//(colors instanceof Array);    //is the variable colors an Array?
//(pattern instanceof RegExp);  //is the variable pattern a RegExp?
/*from   w ww .j ava 2  s. co  m*/
var person = new Object();
var colors = new Array();
console.log(person instanceof Object); 
//is the variable person an Object? 
console.log(colors instanceof Array); 
//is the variable colors an Array? 

All reference values are instances of Object, so objectReference instanceof Object always returns true.

Similarly, primitiveTypeVariable instanceof Object will always return false.

The code above generates the following result.

typeof vs instanceof

The typeof operator tells if a variable is 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".


var s = "XML";
var b = true;
var i = 2;
var u;
var n = null;
var o = new Object();
/*from  w ww. jav  a2 s.  co m*/
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

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

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions