JS: Determine Type of Object

By Xah Lee. Date: . Last updated: .

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:

Reflect.apply ( Object.prototype.toString , obj, [] )

or

Object.prototype.toString.call ( obj )

The obj can be any value, object type or not, such as 3.

const x = /123/;

console.log (
Object.prototype.toString.call ( x ) === "[object RegExp]"
);

console.log (
Reflect.apply ( Object.prototype.toString , x, [] ) === "[object RegExp]"
);

The result is one of the following:

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

Reflect.apply ( Object.prototype.toString , obj, [] )

Applies the function Object.prototype.toString and passing obj as thisBinding, with no argument.

Object.prototype.toString.call(obj) does the same.

[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

  1. Value Types
  2. Primitive Value
  3. Object Type
  4. “typeof” Operator
  5. Find Object's Type
  6. Object.prototype.isPrototypeOf
  7. Property Key “constructor”
  8. “instanceof” Operator

JS Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Find Object's Type
  4. Prototype Chain
  5. Create Object
  6. Object Literal Expr
  7. Create Object with Parent X
  8. Get/Set Parent
  9. Show Prototype Chain
  10. Prevent Adding Property
  11. Clone Object
  12. Test Object Equality
  13. Add Method to Prototype

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials