Languages
[Edit]
EN

JavaScript - check type of object

17 points
Created by:
Giles-Whittaker
739

In this article, we are going to show how to check object type in JavaScript.

Quick solution:

 

There are three different ways how to do it.

The most common way is to use typeof or instanceof operators, rarely toString():

typeof variable

variable instanceof Class

variable instanceof Function

variable.toString()

Result type: string

e.g.

  • undefined
  • boolean
  • number
  • string
  • object
  • function
  • bigint
  • symbol
  • etc. 

Result type: boolean

Result type: string

e.g.

[object Object]

Object means object type.

 

Check the below table to see an example results summary of different approaches.

Note: in the first impression the results of the operator could be strange.

Summary:

1. typeof operator example

Edit

In this section, we use typeof operator to show what kind of type is some object.

Simple types and undefined were marked in comments with ----->

2. Object.prototype.toString method example

Edit

In this section, we used toString method to show how to get a type name. The reason why we used Object.prototype.toString.call() approach to call it is the prevention of local method overloading. 

3. instanceof operator example

Edit

Another way to check the type of object is to use instanceof operator that returns true or false.

false results were marked in comments with ----->

Note: main disadvantage of this approach is we are able just to test objest with some type.

 

Alternative titles

  1. JavaScript - typeof and instanceof operators comparison
  2. JavaScript - typeof and instanceof result table for date, boolean, number, string, function, etc.
  3. JavaScript - typeof object
  4. JavaScript - how to check type of object?
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join