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"

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: 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 Symbol Tutorial]

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 thisBinding, with no argument.

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

[see 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 Object.prototype.toString]

JavaScript Value Types

JavaScript Object and Inheritance

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc