How to get type of an object in JavaScript:

As you know, we can create an object of any function using new keyword. Some time you want to know a type of an object to do some process ahead. Use typeof operator to get the type of an object or variable in JavaScript.

Example: typeof
            
var str = "this is string";

typeof str; // returns string

the typeof operator also returns object type created with new keyword.

Example: typeof

var obj = new String();
var str = "this is string";
            
typeof obj; // returns object
typeof str; // returns string

As you can see in the above example, typeof operator returns different type for literal string and string object.

The same way, you can find type of any variable.

Example: typeof

function myFunc(){
    "HelloWorld");
}

var obj = new myFunc ();
var bool = false;
var num = 100;
var jsObj = {};
var undef;
var nullObj = null;

typeof obj;
typeof bool;
typeof num;
typeof jsObj;
typeof undef;
typeof nullObj;    

You can comapre type using === operator.

Example: typeof

var str = "this is str";
var num = 100;

if (typeof str === "string"){
    alert("str is a string type");
}
if (typeof num === "number"){
    alert("num is a number type");
}

The typeof operator can return following types.

  • string
  • number
  • boolean
  • undefined
  • object
  • function