JS: Determine Type of Object

By Xah Lee. Date: . Last updated: .

How to determine the “type of an object”?

That is, how to find out if a object is function, array, date, regex, etc?

Check If Object is Array

Array.isArray(obj) → returns true for true array.

[see JS: Array-Like Object]

Check If Object is Function

typeof obj === "function"

Other

The most reliable and generic way to determine the type of object is this:

Object.prototype.toString.call ( obj )

The obj can be any value, such as 3.

The result is one of the following:

(there are more, such as WeakMap, WeakSet, Proxy, Promise, etc)

[see JS: Object.prototype.toString]

WARNING: If a obj is a object type, and has a symbol key property Symbol.toStringTag, either own property or inherited, and if its value is a string, let's say tag, then the result of Object.prototype.toString.call ( obj ) is the string:

"[object tag]"

[see JS: Symbol Tutorial]

For detail, see JS: Object.prototype.toString

How Does it Work

Object.prototype.toString.call(obj) is using the method Object.prototype.toString on the object obj.

[see JS: Function Call, Apply, Bind]

We don't want to do obj.toString() because object may have its own toString property therefore overrides the Object.prototype.toString.

[see JS: Object.prototype.toString]

JS Types Topic

  1. JS: Value Types
  2. JS: Primitive Value
  3. JS: Object Type
  4. JS: “typeof” Operator
  5. JS: Determine Type of Object
  6. JS: Object.prototype.isPrototypeOf
  7. JS: Property Key “constructor”
  8. JS: “instanceof” Operator

Object and Inheritance Topic

  1. JS: Object Overview
  2. JS: Object Type
  3. JS: Determine Type of Object
  4. JS: Object Literal Expression
  5. JS: Prototype and Inheritance
  6. JS: Create Object
  7. JS: Create Object with Parent X
  8. JS: Get/Set Prototype
  9. JS: Prevent Adding Property
  10. JS: Clone, Deep Copy Object/Array
  11. JS: Test Equality of Objects
  12. JS: Object Object
  13. JS: Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.