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

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]

Warning: Do Not Use 「typeof」, 「instanceof」, 「constructor」

Note: typeof does not work, because it doesn't distinguish different types of objects. See: JS: Data Types.

Note: do not use instanceof, because it doesn't work. See: JS: “instanceof” Operator.

Note: do not use property "constructor", because it doesn't work. See: JS: Property Key "constructor"

Object and Inheritance Topic

  1. JS: Object System Overview
  2. JS: What's Object?
  3. JS: Prototype and Inheritance
  4. JS: Create Object
  5. JS: Object Literal Expression
  6. JS: Find Object's Prototype
  7. JS: Set Object's Prototype
  8. JS: How to Create Object with Parent X?
  9. JS: Prevent Adding Property
  10. JS: Determine Type of Object
  11. JS: Primitive Value Object Wrapper
  12. JS: Clone, Deep Copy Object/Array
  13. JS: Test Equality of Objects

  1. JS: Object Object
  2. JS: Object.prototype
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth