Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

How to get 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
Try it

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
Try it

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(){
    "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;
Try it

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");
}
Try it

The typeof operator can return the following types:

  • string
  • number
  • boolean
  • undefined
  • object
  • function
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.