How to know the type of an object in JavaScript?

As you know, we can create an object of any function using the new keyword. Sometimes you want to know the type of an object to perform some action on it. Use the 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 the object type created with the "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, the typeof operator returns different types for a literal string and a string object.

In the same way, you can find the type of any variable.

Example: typeof
function myFunc(){

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 compare the type using the === 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 the following types:

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