JavaScript: 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)
Return true for true array. [see Array-Like Object]

Check If Object is Function

typeof obj === "function"

(also works on Arrow Function)

Other

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

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

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

const fGetType = ((x) => Reflect.apply(Object.prototype.toString, x, []));

console.log(
  fGetType({}) === "[object Object]" &&
    fGetType([]) === "[object Array]" &&
    fGetType(/./) === "[object RegExp]" &&
    fGetType(new Date()) === "[object Date]" &&
    fGetType(function f() {}) === "[object Function]" &&
    fGetType((x) => 3) === "[object Function]" &&
    fGetType(1) === "[object Number]" &&
    fGetType("") === "[object String]" &&
    fGetType(true) === "[object Boolean]" &&
    fGetType(new Set()) === "[object Set]" &&
    fGetType(new Map()) === "[object Map]",
);
// true

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 on obj is the string:

"[object tag]"

For detail, see Object.prototype.toString

How Does it Work

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

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

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

[see Object.prototype.toString]

[see Reflect.apply]

JavaScript Value Types

JavaScript Object and Inheritance

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc