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

JS Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Prototype and Inheritance
  4. Create Object
  5. Object Literal Expression
  6. Create Object with Parent X
  7. Get/Set Prototype
  8. Prevent Adding Property
  9. Determine Type of Object
  10. Clone Object
  11. Test Object Equality
  12. Add Method to Prototype
  13. Object Object
  14. 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.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog